当前位置:网站首页>[sword finger offer] 60 Points of N dice

[sword finger offer] 60 Points of N dice

2022-07-06 18:18:00 LuZhouShiLi

The finger of the sword Offer 60. n The number of dice

subject

  hold n A dice on the ground , The sum of the points on the up side of all dice is s. Input n, Print out s The probability that all possible values of the . You need to return the answer with an array of floating-point numbers , Among them the first i The elements represent this n The number of points that a die can roll i The probability of the smaller one .

Ideas

  • First, use the first dimension of the array to represent the stage , That is, throw a few dice
  • Then use the second dimension representation of the array to roll these dice , Possible points
  • The value of the array represents , The number of points in this stage

Code

class Solution {
    
public:
    vector<double> dicesProbability(int n) {
    
        int dp[12][70];
        memset(dp,0,sizeof(dp));//  All initialization 0

        for(int i = 1; i <= 6; i++)
        {
    
            dp[1][i] = 1;//  Status array initialization 
        }

        for(int i = 2; i <= n; i++)
        {
    
            //  The maximum number of points   It must be  6 * i
            for(int j = i; j <= 6 * i; j++)
            {
    
                for(int cur = 1; cur <= 6; cur++)
                {
    
                    if(j - cur <= 0)
                    {
    
                        break;
                    }
                    //  But look No i A dice , Points may be 1 2 3 4 5 6  So points j The number of occurrences is determined by the end of the throw  i - 1 A dice   Corresponding points  j - 1 j - 2 j - 6  The sum of the number of occurrences is transformed 
                    dp[i][j] += dp[i - 1][j - cur];
                }
            }
        }

        int all = pow(6,n);//  All possibilities 
        vector<double>  ret;
        for(int i = n; i <= n * 6; i++)
        {
    
            ret.push_back(dp[n][i] * 1.0 /  all);
        }
        return ret;
    }
};
原网站

版权声明
本文为[LuZhouShiLi]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207061011051341.html