标签:
1 int g_maxValue=6; 2 void PrintProbability(int number) 3 { 4 if(number<1) 5 return; 6 int maxSum=num*g_maxValue; 7 int* pProbabilities=new int[maxSum-number+1]; 8 for(int i=number;i<=maxSum;++i) 9 pProbabilities[i-number]=0; 10 Probability(number,pProbabilities); 11 int total=pow((double)g_maxValue,number); 12 for(int i=number;i<=maxSum;++i) 13 { 14 double ratio=(double)pProbabilities[i-number]/total; 15 printf("%d:%e\n",i,ratio); 16 } 17 delete []probabilities; 18 } 19 20 void Probability(int number,int* pProbabilities) 21 { 22 for(int i=1;i<=g_maxValue;++i) 23 Probability(number,number,i,pProbabilities); 24 } 25 26 void Probability(int original,int current,int sum,int* pProbabilities) 27 { 28 if(current==1) 29 { pProbabilities[sum-original]++; } 30 else 31 { 32 for(int i=1;i<=g_maxValue;++i) 33 {Probabilitiey(original,current-1,i+sum,pProbabilities);} 34 } 35 }
上述思路很简洁,实现起来很容易。但由于是基于递归实现,它有很多的计算是重复的,从而导致当number变大时性能慢得让人不能接受.
1 int g_maxValue=6; 2 void PrintProbability(int number) 3 { 4 if(number<1) return; 5 int *pProbabilities[2]; 6 pProbabilities[0]= new int[g_maxValue*number+1]; 7 pProbabilities[1]=new int[g_maxValue*number+1]; 8 for(int i=0;i<g_maxValue*number+1;++i) 9 { 10 pProbabilities[0][i]=0; 11 pProbabilities[1][i]=0; 12 } 13 14 int flag=0; 15 for(int i=1;i<=g_maxValue;++i) 16 pProbabilities[flag][i]=1; 17 18 for(int k=2;k<=number;++k) 19 { 20 for(int i=0;i<k;++i) 21 pProbabilities[1-flag][i]=0; 22 23 for(int i=k;i<=g_maxValue*k;++i) 24 { 25 pProbabilities[1-flag][i]=0; 26 for(int j=1;j<=i&&j<=g_maxValue;++j) 27 pProbabilities[1-flag][i] +=pProbabilities[flag][i-j]; 28 } 29 flag=1-flag; 30 } 31 32 double total=pow((double)g_maxValue,number); 33 for(int i=number;i<=g_maxValue*number;++i) 34 { 35 double ratio=(double)pProbabilities[flag][i]/total; 36 printf("%d:%e\n",i,ratio); 37 } 38 delete []pProbabilities[0]; 39 delete []pProbabilities[1]; 40 }
标签:
原文地址:http://www.cnblogs.com/wxdjss/p/5559424.html