Sword refers to Offer 60. The number of n dice points

Throw n dice on the ground, and the sum of the points on the upward side of all dice is s. Enter n to print out the probabilities of all possible values ​​of s.

You need to use an array of floating-point numbers to return the answer, where the i-th element represents the probability of the i-th smallest in the set of points that can be thrown by the n dice.

Example 1:

Input: 1
Output: [0.16667,0.16667,0.16667,0.16667,0.16667,0.16667]

Example 2:

Input: 2
Output: [0.02778,0.05556,0.08333,0.11111,0.13889,0.16667,0.13889,0.11111,0.08333,0.05556,0.02778]

limit:

1 <= n <= 11

dp record it

class Solution {
    
    
public:
    vector<double> dicesProbability(int n) {
    
    
        vector<double>ve;
        long sum=pow(6,n);
        int dp[12][67];              //定义dp[i][j]为i个骰子投出j点的次数
        memset(dp,0,sizeof(dp));     //那么转移方程则是dp[i][j]=dp[i-1][j-1]+dp[i-1][j-2].....+dp[i-1][j-6]
        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>=1)        //防止出现j ==-1的情况
                    {
    
    
                         dp[i][j]+=dp[i-1][j-k];
                    }
                }
            }
        }
        for(int i=n;i<=6*n;i++)
        {
    
    
            ve.push_back(double(dp[n][i]*1.0/sum));
        }
        return ve;
    }
};

Guess you like

Origin blog.csdn.net/qq_43624038/article/details/113796249