Number of Dice Rolls With Target Sum Problem
Description
LeetCode Problem 1155.
You have n dice, and each dice has k faces numbered from 1 to k.
Given three integers n, k, and target, return the number of possible ways (out of the k^n total ways) to roll the dice, so the sum of the face-up numbers equals target. Since the answer may be too large, return it modulo 10^9 + 7.
Example 1:
Input: n = 1, k = 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: n = 2, k = 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: n = 30, k = 30, target = 500
Output: 222616187
Explanation: The answer must be returned modulo 10^9 + 7.
Constraints:
1 <= n, k <= 301 <= target <= 1000
Solution
Approach: Dynamic Programming over Dice
Trying all kn rolls is far too slow, but we only care about the running sum, not which faces produced it. Let f[i][j] be the number of ways for the first i dice to add up to j.
The last of those i dice shows some face from 1 to k. If it shows face, the other i - 1 dice must add up to j - face, so
f[i][j] = f[i-1][j-1] + f[i-1][j-2] + ... + f[i-1][j-k]
skipping terms where j - face < 0. The base case is f[0][0] = 1: zero dice make a sum of 0 in exactly one way (and no other sum). The answer is f[n][target], taken modulo 109 + 7 at every addition so the numbers stay small.
i dice can never add up to more than i * k, so j only needs to go that far; this also makes a target larger than n * k come out as 0.
Complexity: O(n * k * target) time and O(n * target) space.
class Solution:
def numRollsToTarget(self, n: int, k: int, target: int) -> int:
mod = 10**9 + 7
# f[i][j]: ways for the first i dice to sum to j.
f = [[0] * (target + 1) for _ in range(n + 1)]
f[0][0] = 1
for i in range(1, n + 1):
for j in range(1, min(i * k, target) + 1):
for face in range(1, min(j, k) + 1):
f[i][j] = (f[i][j] + f[i - 1][j - face]) % mod
return f[n][target]