把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
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/nge-tou-zi-de-dian-shu-lcof
方法一:动态规划
当有n个骰子,n<=点数<=6n。
首先计算n个骰子所有可能的情况:6**n
然后计算每个点数都多少种可能的情况:dp[i][j]为i个骰子时,点数为j有多少种可能的情况。则:
dp[i][j]=dp[i-1][j-1]+dp[i-1][j-2]...+...+dp[i-1][j-6]
可以利用循环(递归)去进行求解。
class Solution:
def twoSum(self, n: int) -> List[float]:
# n = 2
min_val = n
max_val = n*6
totol_nums = 6**n
dp = [[0]*(n*6) for i in range(n)]
for i in range(6):
dp[0][i] = 1
for i in range(1, n):
for j in range(i, 6*(i+1)):
for k in range(1, 7):
if j-k>=0:
dp[i][j] += dp[i-1][j-k]
# print(dp)
result = []
for i in range(min_val-1, max_val):
result.append(dp[n-1][i]/totol_nums)
return result