Number of Dice Rolls With Target Sum — LeetCode 1155 Python Solution

MediumDynamic Programming
Problem
#1155
Reading time
2 min

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

Python
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

MeasureComplexity
TimeO(n \times k \times target)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview