Jianzhi offer interview question 60. The number of n dice [simple]-dynamic programming

Interview Question 60. The number of n dice

There are n~6n results for n dice

Each result is related to the result of n-1 dice

Count the first occurrence and then calculate the probability

class Solution {
public:
    vector<double> twoSum(int n) {
        vector<vector<int>> dp(n+1,vector<int>(6*n+1,0));
        for(int i=1;i<=6;i++)
            dp[1][i]=1;
        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<=0)   break;
                    dp[i][j]+=dp[i-1][j-k];
                }
            }
        }
        vector<double> res;
        int tmp=pow(6,n);
        for(int i=n;i<=6*n;i++){
            res.push_back(dp[n][i]*1.0/tmp);
        }
        return res;
    }
};

Guess you like

Origin blog.csdn.net/qq_41041762/article/details/105897068