20. 骰子求和

描述

扔 n 个骰子,向上面的数字之和为 S。给定 n,请列出所有可能的 S 值及其相应的概率。

样例

样例 1:

输入:n = 1
输出:[[1, 0.17], [2, 0.17], [3, 0.17], [4, 0.17], [5, 0.17], [6, 0.17]]
解释:掷一次骰子,向上的数字和可能为1,2,3,4,5,6,出现的概率均为 0.17。

样例 2:

输入:n = 2
输出:[[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]]
解释:掷两次骰子,向上的数字和可能在[2,12],出现的概率是不同的。

题解:

class Solution {
public:
    /**
     * @param n an integer
     * @return a list of pair<sum, probability>
     */
    vector<pair<int, double>> dicesSum(int n) {
        // Write your code here
        vector<pair<int, double>> results;
        vector<vector<double>> f(n + 1, vector<double>(6 * n + 1));

        for (int i = 1; i <= 6; ++i) f[1][i] = 1.0 / 6;
        
        for (int i = 2; i <= n; ++i)
            for (int j = i; j <= 6 * i; ++j) {
                for (int k = 1; k <= 6; ++k)
                    if (j > k)
                        f[i][j] += f[i - 1][j - k];
                f[i][j] /= 6.0;
            }

        for (int i = n; i <= 6 * n; ++i)
            results.push_back(make_pair(i, f[n][i]));

        return results;
    }
};
posted @ 2020-12-02 22:38  你的深渊  阅读(190)  评论(0编辑  收藏  举报