Sword refers to the points of Offer 60-n dice C++

Title description

Insert picture description here

Solution dp

  1. The meaning of the dp array
    dp[i][j] represents the total number of casting methods of the number j of i dice , each dice is special, and the total method is guaranteed to be 6 to the nth power.
  2. dp equation
    dp[i][j] = dp[i-1][j-k] k<j and k∈[1,6]
    such as dp[3][8] = dp[2][2]+dp [2][3]…dp[2][7]
    dp[3][3]=dp[2][1] + dp[2][2]
    3. Initial value
    dp[1][1] = dp [1][2] = …dp[1][6] = 1
    4. The final result
    dp[n][n], dp[n][n + 1], dp[n][n + 2]… dp [n][6 * n]
class Solution {
    
    
public:
    vector<double> dicesProbability(int n) {
    
    
        //dp[i][j]:i个骰子投出数字为j的结果个数
        //dp[i][j] = dp[i - 1][j-k] k∈[1,6] 
        vector<double> ans(6 * n - n + 1, 0);
        vector<vector<int>> dp(n + 1,vector<int>(6 * n + 1, 0));
        
        for(int k = 1; k <= 6; k++) dp[1][k] = 1;
        
        for(int i = 2; i <= n; i++) {
    
    
            for(int j = i; j <= 6 * i; j++) {
    
    
                for(int k = 1; k <= 6 && k < j; k++) {
    
    
                    dp[i][j] += dp[i - 1][j - k];
                }
            }
        }
        int base = pow(6,n);
        for(int i = n; i <= 6*n ; i ++) ans[i - n] = dp[n][i] * 1.0 /base;
        return ans;
    }
};

Insert picture description here
Time complexity O(N^2)
Space complexity O(N^2)

Guess you like

Origin blog.csdn.net/qq_42883222/article/details/112667931