剑指 Offer 60. n个骰子的点数
1 题目描述
- 题目链接:剑指 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]
2 思路
采用动态规划,当骰子数为n
时,所有骰子的总点数即为x
,其对应的概率设为f[n][x]
,则应该有:
因此,不难写出以下代码:
class Solution {
public:
vector<double> dicesProbability(int n) {
double dp[n+1][6*n+1];
memset(dp, 0, sizeof(dp));
for(int i = 1; i <= 6; ++i){
dp[1][i] = 1 / 6.0;
}
for(int i = 2; i <= n; ++i){
for(int j = i; j <= i*6; ++j){
for(int k = 1; k <= 6&& k < j; ++k){
dp[i][j] += dp[i-1][j-k] / 6.0;
}
}
}
vector<double> res;
for(int i = n; i <= n * 6; ++i){
res.emplace_back(dp[n][i]);
}
return res;
}
};
- 优化存储空间:在遍历骰子时创建数组,然后遍历完成后将数组赋给答案数组。
class Solution {
public:
vector<double> dicesProbability(int n) {
vector<double> res(6, 1.0 / 6);
for(int i = 2; i <= n; ++i){
vector<double> tmp(5 * i + 1, 0);
for(int j = 0; j < res.size(); ++j){
for(int k = 0; k < 6; ++k){
tmp[j+k] += res[j] / 6.0;
}
}
res = tmp;
}
return res;
}
};