剑指 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
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/nge-tou-zi-de-dian-shu-lcof
思路解析
记\(n\)个骰子,点数和为\(s\)的概率为\(P(n,s)\),易得以下递推关系:
\[P(n,s) = \frac{1}{6} \cdot \sum_{i = 1}^6 P(n-1,s-i)
\]
上式为动态规划状态转移方程,使用二维矩阵存储\(P(n,s)\)的值。
代码实现
class Solution {
public:
vector<double> twoSum(int n) {
int s = n * 6;
vector<vector<double>> probability_mat(n + 1, vector<double>(s + 1, 0));
double base_p = 1.0 / 6.0;
for(int i = 1; i <= 6; i++)
probability_mat[1][i] = base_p;
for(int dice = 2; dice <= n; dice++) {
for(int ts = 1; ts <= s; ts++) {
for(int i = 1; i <= 6; i++)
if(i <= ts)
probability_mat[dice][ts] += probability_mat[dice - 1][ts - i] / 6.0;
}
}
vector<double> result;
for(int i = 0; i < s + 1; i++) {
if(probability_mat[n][i] > 0)
result.push_back(probability_mat[n][i]);
}
return result;
}
};