标签:style blog http os io 2014 for art
问题描述:打一枪可能的环数为0~10,求打10枪总环数为90的概率。
这是一道排列组合问题,可以用循环加递归的方法解决。比如,第一次可以打出0~10环,那么先固定第一次打的环数,然后加上剩下的九次打的环数,就得到总环数。而剩下九次的环数通过递归很容易求得。代码如下:
#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; // 第index枪环数为i Permutation(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; }
#include <iostream> using namespace std; int cnt = 0; int target = 90; void Permutation(int *numbers, int index, int length) { int PartSum = 0; // 已有环数 int Left = 0; // 还需要多少环才能达到90 for (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; // 第index枪环数为i Permutation(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; }
标签:style blog http os io 2014 for art
原文地址:http://blog.csdn.net/nestler/article/details/38170611