把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

Python 解答:
1.暴力

class Solution:
    def dicesProbability(self, n: int) -> List[float]:
        digit = [1, 2, 3, 4, 5, 6]
        nums = [0 for i in range(n, 6*n+1)]

        def backtrace(digit, n, res, p):
            if n == 0:
                nonlocal nums
                nums[res-p] += 1
                return 
            for item in digit:
                res += item
                backtrace(digit, n-1, res, p)
                res -= item
        backtrace(digit, n, 0, n)
        total = pow(6, n)
        for i in range(len(nums)):
            nums[i] /= total
        return nums

2.动态规划

class Solution:
    def dicesProbability(self, n: int) -> List[float]:
        P = [1/6 for i in range(6)]
        if n == 1:
            return P 
        else:
            k = 2
            while k <= n:
                newlist = [0 for i in range(6*k-k+1)]
                for i in range(len(P)):
                    for j in range(6):
                        newlist[i+j] += P[i]/6
                P = newlist
                k += 1
        return P
最后修改日期: 2021年4月16日

留言

撰写回覆或留言

发布留言必须填写的电子邮件地址不会公开。