美文网首页
20. Dice Sums

20. Dice Sums

作者: swordofAltair | 来源:发表于2018-07-16 10:02 被阅读0次

    Description
    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
    Given n = 1, return [ [1, 0.17], [2, 0.17], [3, 0.17], [4, 0.17], [5, 0.17], [6, 0.17]].

    思路:直接DP即可。不需处理精度。

    Code:

    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
            double a[100][600]={0};
            for(int i=1;i<=6;i++){
                a[1][i]=1.00/6;
            }
            for (int i = 2;i <= n;i++){
                for (int j = i;j<=6 * n;j++){
                    double temp = 0;
                    for (int k = 1;k<=6;k++){
                        temp += a[i - 1][j - k] * a[1][k];
                    }
                    a[i][j] = temp;
                }
            }
            vector<pair<int,double>> ans;
            for(int i=n;i<=6*n;i++){
                pair<int,double> temp(i,a[n][i]);
                ans.push_back(temp);
            }
            return ans;
        }
    };
    

    相关文章

      网友评论

          本文标题:20. Dice Sums

          本文链接:https://www.haomeiwen.com/subject/hypvpftx.html