Problem
You have d d d dice, and each die has f f f faces numbered 1, 2, …, f.
Return the number of possible ways (out of fd total ways) modulo 10^9 + 7 to roll the dice so the sum of the face up numbers equals target.
Example 1:
Input: d = 1, f = 6, target = 3
Output: 1
Explanation:
You throw one die with 6 faces. There is only one way to get a sum of 3.
Example 2:
Input: d = 2, f = 6, target = 7
Output: 6
Explanation:
You throw two dice, each with 6 faces. There are 6 ways to get a sum of 7:
1+6, 2+5, 3+4, 4+3, 5+2, 6+1.
Example 3:
Input: d = 2, f = 5, target = 10
Output: 1
Explanation:
You throw two dice, each with 5 faces. There is only one way to get a sum of 10: 5+5.
Example 4:
Input: d = 1, f = 2, target = 3
Output: 0
Explanation:
You throw one die with 2 faces. There is no way to get a sum of 3.
Example 5:
Input: d = 30, f = 30, target = 500
Output: 222616187
Explanation:
The answer must be returned modulo 10^9 + 7.
Constraints:
- 1 <= d, f <= 30
- 1 <= target <= 1000
解题思路
这道题也是一道十分典型的动态规划的题目,我们可以将 d d d个骰子看作一个骰子投掷了 d d d次,那么,每投掷一次,都会和之前的投掷结果相关联。所以,我们可以定义一个二维数组 d p dp dp,行表示投掷的次数,列表示投掷的数目之和, d p [ i ] [ j ] dp[i][j] dp[i][j]表示一共投掷 i i i次骰子时候所有数字之和为 j j j的可能组合的数目。由于一个骰子只有 f f f个面,因此需要求 d p [ i ] [ j ] dp[i][j] dp[i][j], 我们只需要遍历 j j j前面的 f f f个数据即可,即:
d p [ i ] [ j ] = s u m ( d p [ i − 1 ] [ k ] f o r j − k < f a n d k > 0 ) dp[i][j] = sum(dp[i - 1][k] \quad for \quad j - k < f \quad and \quad k > 0) dp[i][j]=sum(dp[i−1][k]forj−k<fandk>0)
代码如下:
class Solution:
def numRollsToTarget(self, d: int, f: int, target: int) -> int:
dp = [[0 for i in range(target + 1)] for j in range(d)]
for i in range(f):
if i + 1 <= target:
dp[0][i + 1] = 1
for i in range(1, d):
for j in range(1, target + 1):
k = 1
while j - k > 0 and k <= f:
dp[i][j] += dp[i - 1][j - k]
k += 1
return dp[-1][-1] % (1000000000+7)