【leetcode刷题】面试题60. n个骰子的点数

面试题60. n个骰子的点数
把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

class Solution {
     
public:
    vector<double> twoSum(int n) {
     
        vector<double> result;
        int a[70]={
     0};
        int all = pow(6, n);
        for(int i=1;i<=6;i++)
        {
     
            a[i] = 1;
        }
            
        for(int i=2; i<=n; i++)
        {
     
            for(int j=i*6; j>=i; j--)
            {
     
                a[j] = 0;
                for(int k=1; k<=6; k++)
                {
     
                    if(k+(i-1) > j)     //第j个骰子的点数k,加上前j-1个骰子最小点数(i-1)大于当前计算的点数。说明更大的点数都会大于当前计算的点数,直接中断后面的计算
                        break;
                    else
                        a[j] += a[j-k];
                }
            }
        }
        
        for (int i = n; i <= 6 * n; i ++) {
     
            result.push_back(a[i] * 1.0 / all);
        }

        
        
        return result;
    }
};

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/nge-tou-zi-de-dian-shu-lcof

你可能感兴趣的:(leetcode,算法,leetcode,动态规划)