LintCode 20: Dices Sum (DP + 概率题)

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;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值