20. Dices Sum
Throw n dices, the sum of the dices' faces is S. Given n, find the all possible value of S along with its probability.
Example
Example 1:
Input: n = 1
Output: [[1, 0.17], [2, 0.17], [3, 0.17], [4, 0.17], [5, 0.17], [6, 0.17]]
Explanation: Throw a dice, the sum of the numbers facing up may be 1, 2, 3, 4, 5, 6, and the probability of each result is 0.17.
Example 2:
Input: n = 2
Output: [[2,0.03],[3,0.06],[4,0.08],[5,0.11],[6,0.14],[7,0.17],[8,0.14],[9,0.11],[10,0.08],[11,0.06],[12,0.03]]
Explanation: Throw two dices, the sum of the numbers facing up may be in [2,12], and the probability of each result is different.
Notice
You do not care about the accuracy of the result, we will help you to output results.
Input test data (one parameter per line)How to understand a testcase?
解法1:DP
class Solution {
public:
/**
* @param n an integer
* @return a list of pair<sum, probability>
*/
vector<pair<int, double>> dicesSum(int n) {
vector<pair<int, double>> results;
//dp[i][j]: the prob of the ith throw, and get the sum j.
vector<vector<double>> dp(n + 1, vector<double>(6 * n + 1));
for (int i = 1; i <= 6; ++i) dp[1][i] = 1.0 / 6;
for (int i = 2; i <= n; ++i) {
//throw i times, the sum range is [i .. 6 * i]
for (int j = i; j <= 6 * i; ++j) {
for (int k = 1; k <= 6; ++k) {
if (j >= k) dp[i][j] += dp[i - 1][j - k];
}
dp[i][j] /= 6.0;
}
}
for (int i = n; i <= 6 * n; ++i) {
results.push_back({i, dp[n][i]});
}
return results;
}
};