Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[剑指 Offer] 60. n个骰子的点数 #85

Open
frdmu opened this issue Aug 20, 2021 · 0 comments
Open

[剑指 Offer] 60. n个骰子的点数 #85

frdmu opened this issue Aug 20, 2021 · 0 comments

Comments

@frdmu
Copy link
Owner

frdmu commented Aug 20, 2021

把n个骰子扔在地上,所有骰子朝上一面的点数之和为s。输入n,打印出s的所有可能的值出现的概率。

 

你需要用一个浮点数数组返回答案,其中第 i 个元素代表这 n 个骰子所能掷出的点数集合中第 i 小的那个的概率。

 

示例 1:

输入: 1
输出: [0.16667,0.16667,0.16667,0.16667,0.16667,0.16667]

示例 2:

输入: 2
输出: [0.02778,0.05556,0.08333,0.11111,0.13889,0.16667,0.13889,0.11111,0.08333,0.05556,0.02778]

限制:

  • 1 <= n <= 11

解法:
动态规划。搞一个二维数组dp[i][j],表示i个骰子点数为j时的概率。图示如下:
无标题
代码如下:

class Solution {
public:
    vector<double> dicesProbability(int n) {
        vector<vector<double>>  dp(n+1, vector<double>(6*n+1, 0));
        vector<double> res;

        for (int i = 1; i < 7; i++) {
            dp[1][i] = 1.0 / 6;
        }   
        for (int i = 1; i < n; i++) {
            for (int j = i; j <= 6*i; j++) {
                for (int s = 1; s < 7; s++) {
                    dp[i+1][j+s] += dp[i][j] * 1.0 / 6;
                }    
            }
        }
        for (int i = n; i <= 6*n; i++) {
            res.push_back(dp[n][i]);
        }

        return res;
    }
};

Refer:
剑指 Offer 60. n 个骰子的点数(动态规划,清晰图解)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant