剑指 Offer 60. n个骰子的点数
题目描述:
把n个骰子扔在地上,所有骰子朝上一面的点数之和为s。输入n,打印出s的所有可能的值出现的概率。
你需要用一个浮点数数组返回答案,其中第 i 个元素代表这 n 个骰子所能掷出的点数集合中第 i 小的那个的概率。
示例 1:
输入: 1
输出: [0.16667,0.16667,0.16667,0.16667,0.16667,0.16667]
示例 2:
输入: 2
输出: [0.02778,0.05556,0.08333,0.11111,0.13889,0.16667,0.13889,0.11111,0.08333,0.05556,0.02778]
限制:
1 <= n <= 11
解:
//可能的点数1n ~ 6n
//dp[i][j]表示i个骰子骰出点数j的方案个数
//dp[i][j] = dp[i-1][j-1] + dp[i-1][j-2] + dp[i-1][j-3] + dp[i-1][j-4] + dp[i-1][j-5] + dp[i-1][j-6]
class Solution {
public:
vector<double> twoSum(int n) {
//dp[i][j]表示i个骰子骰出点数j的方案个数
vector<vector<int>> dp(n+1,vector<int>(6*n+1,0)); //注意大小
//已知条件
for(int i = 1;i <= 6;++i)
dp[1][i] = 1;
for(int i = 2;i <= n;++i)
{
for(int j = i;j <= 6*i;++j)
{
//dp[i][j] = dp[i-1][j-1] + dp[i-1][j-2] + dp[i-1][j-3] + dp[i-1][j-4] + dp[i-1][j-5] + dp[i-1][j-6]
int x = j < 6 ? j-1 : 6; //点数j不满6点处理
for(int y = 1;y <= x;++y)
dp[i][j] += dp[i-1][j-y];
}
}
vector<double> res;
double mother = pow(6,n); //6^n
for(int j = n;j <= 6*n;++j)
{
res.push_back(dp[n][j]/mother);
}
return res;
}
};