分析:
动态规划的思想:
1.现在变量有:骰子个数,点数和。当有k个骰子,点数和为n时,出现次数记为f(k,n)。那与k-1个骰子阶段之间的关系是怎样的?
2.当我有k-1个骰子时,再增加一个骰子,这个骰子的点数只可能为1、2、3、4、5或6。那k个骰子得到点数和为n的情况有:
(k-1,n-1):第k个骰子投了点数1
(k-1,n-2):第k个骰子投了点数2
(k-1,n-3):第k个骰子投了点数3
….
(k-1,n-6):第k个骰子投了点数6
在k-1个骰子的基础上,再增加一个骰子出现点数和为n的结果只有这6种情况!
所以:f(k,n)=f(k-1,n-1)+f(k-1,n-2)+f(k-1,n-3)+f(k-1,n-4)+f(k-1,n-5)+f(k-1,n-6)
代码:
#include <iostream>
using namespace std;
//全局变量
int g_max_value = 6;
void PrintProbabilityOfDices(int number, int g_max_value)
{
if (number < 1)
return;
int** pProbility = new int*[2];
pProbility[0] = new int[number*g_max_value + 1];
pProbility[1] = new int[number*g_max_value + 1];
//初始化
for (int i = 0; i < number*g_max_value + 1; ++i)
{
pProbility[0][i] = 0;
pProbility[1][i] = 0;
}
for (int i = 1; i <= g_max_value; ++i) //第一个骰子
{
pProbility[0][i] = 1;
}
for (int k = 2; k <= number; ++k) //从第2个骰子开始循环
{
for (int i = 0; i < k; ++i)
{
pProbility[1][i] = 0;
}
for (int i = k; i <= k*g_max_value; ++i)
{
for (int j = 1; j <= i && j <= g_max_value; ++j)
{
pProbility[1][i] += pProbility[0][i - j];
}
}
//交换两个数组
int* temp = nullptr;
temp = pProbility[0];
pProbility[0] = pProbility[1];
pProbility[1] = temp;
}
//计算概率
double total = (double)pow(g_max_value, number);
for (int i = number; i < number*g_max_value + 1; ++i)
{
double ratio = (double)pProbility[0][i] / total;
cout << "和为" << i << "的概率为: " << ratio << endl;
}
}
int main()
{
int number = 2;
PrintProbabilityOfDices(2, g_max_value);
cout << endl;
system("pause");
return 0;
}
测试: