lintcode: Dices Sum

来源:互联网 发布:明朝穿越小说 知乎 编辑:程序博客网 时间:2024/06/05 14:16

Throw n dices, the sum of the dices' faces is S. Given n, find the all possible value of S along with its probability.

 Notice

You do not care about the accuracy of the result, we will help you to output results.

Example

Given n = 1, return [ [1, 0.17], [2, 0.17], [3, 0.17], [4, 0.17], [5, 0.17], [6, 0.17]].


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<vector<double>> dp(n+1, vector<double>(n*6+1));                for (int i=0; i<=n; i++)            for (int j=0; j<=n*6; j++)                dp[i][j] = 0.0;                        for (int k=1; k<=6; k++)            dp[1][k] = 1.0 / 6.0;                    for (int i=2; i<=n; i++)        {            for (int j=1; j<=6*n; j++)            {                for (int k=1; k<=6; k++)                {                    if (j > k)                    {                        dp[i][j] += dp[i-1][j-k];                    }                }                dp[i][j] = dp[i][j] / 6.0;            }        }                vector<pair<int, double>> retVtr;        for (int j=n; j<=6*n; j++)        {            pair<int, double> p = make_pair(j, dp[n][j]);            retVtr.push_back(p);        }                return retVtr;    }};


原创粉丝点击