Number of Dice Rolls With Target Sum — LeetCode 1155 Python Solution
- Problem
- #1155
- Pattern
- Dynamic Programming
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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 kn total ways) to roll the dice, so the sum of the face-up numbers equals target.
Example
- Input
- n = 1, k = 6, target = 3
- Output
- 1
- Explanation
- You throw one die with 6 faces.
Python solution
class Solution:
def numRollsToTarget(self, n: int, k: int, target: int) -> int:
f = [[0] * (target + 1) for _ in range(n + 1)]
f[0][0] = 1
mod = 10**9 + 7
for i in range(1, n + 1):
for j in range(1, min(i * k, target) + 1):
for h in range(1, min(j, k) + 1):
f[i][j] = (f[i][j] + f[i - 1][j - h]) % mod
return f[n][target]Complexity
| Measure | Complexity |
|---|---|
| Time | O(n \times k \times target) |
| Space | O(n \times target) auxiliary |
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1155. Number of Dice Rolls With Target Sum is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1155. Number of Dice Rolls With Target Sum?
- LeetCode 1155. Number of Dice Rolls With Target Sum is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1155. Number of Dice Rolls With Target Sum?
- The Python solution on this page runs in O(n \times k \times target).
- What is the space complexity of LeetCode 1155. Number of Dice Rolls With Target Sum?
- The Python solution on this page uses O(n \times target) auxiliary space.
- What topics does LeetCode 1155. Number of Dice Rolls With Target Sum cover?
- LeetCode 1155. Number of Dice Rolls With Target Sum is tagged Dynamic Programming on LeetCode.