MediumNo. 1155

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

Topics
Dynamic Programming
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

PythonSolution
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

Time
O(n × k × target)
Space · auxiliary
O(n × target)

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

Related problems
No.ProblemDifficulty
1162As Far from Land as PossibleMedium
0010Regular Expression MatchingHard
0022Generate ParenthesesMedium
0032Longest Valid ParenthesesHard
0044Wildcard MatchingHard
0045Jump Game IIMedium

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 × k × 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 × 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.

Free to download. Check it runs on your machine, then pick a plan.