Problem description: the possible number of rings for a single shot is 0 ~ 10. Calculate the probability that the total number of rings is 90.
This is a problem of arrangement and combination, which can be solved by repeating and recursion. For example, you can play 0 ~ For 10 rings, first set the number of rings played for the first time, and then add the number of the remaining nine rings to get the total number of rings. The number of loops for the remaining nine times is easily obtained through recursion. The Code is as follows:
# Include <iostream> using namespace STD; int CNT = 0; int target = 90; void permutation (int * numbers, int index, int length) {If (Index = length) {int sum = 0; For (INT I = 0; I <length; I ++) sum + = numbers [I]; If (sum = target) CNT ++;} else {for (INT I = 0; I <= 10; I ++) {numbers [Index] = I; // The index gun ring number is ipermutation (numbers, index + 1, length); }}int main () {int numbers [10] = {0}; permutation (numbers, 0, 10); cout <(CNT/POW (11, 10) * 100 <Endl; System ("pause"); Return 0 ;}
After running this program for a long time, there was no result. It was a tragedy... The above code is equivalent to a 10-layer nested loop, which is efficient. Is there any optimization solution? Actually, there are. In the following two cases, recursion can return in advance:
- If the number of rings is greater than 90
- Even if every remaining gun hits 10 rings, it cannot reach 90 rings.
Based on the above two situations, I optimized the Code:
# Include <iostream> using namespace STD; int CNT = 0; int target = 90; void permutation (int * numbers, int index, int length) {int partsum = 0; // number of existing loops int left = 0; // The number of loops required to reach 90for (INT I = 0; I <index; I ++) partsum + = numbers [I]; left = target-partsum; If (partsum> Target | (length-index) * 10 <left) return; If (Index = length) {int sum = 0; for (INT I = 0; I <length; I ++) sum + = numbers [I]; If (sum = target) CNT ++ ;} else {for (INT I = 0; I <= 10; I ++) {numbers [Index] = I; // The number of index gun rings is ipermutation (numbers, index + 1, length) ;}}int main () {int numbers [10] = {0}; permutation (numbers, 0, 10 ); cout <(CNT/POW (11, 10) * 100 <Endl; System ("pause"); Return 0 ;}
Running result:
Finally, the result is returned. The optimized code does not know where the efficiency is!
This problem is very similar to the eight queens problem. First, find all the situations, and then remove the non-conforming situations or record the situations that meet the requirements.