Number of Dice Rolls With Target Sum (LeetCode 1155): Solution and Explanation

Medium
Dynamic Programming

Count the ways n dice with faces 1..k can add up to target, where the dice are told apart (1+6 and 6+1 are different). Return the count modulo 10^9 + 7.

Intuition

Rolling all n dice at once is hard to count, but adding them one at a time is easy. Before the last die is rolled, the others have some total. If the last die shows f, that total must have been target - f.

So the number of ways to reach a sum s with i dice is the sum, over every face f, of the ways to reach s - f with i - 1 dice. Each face leads to a different roll, so nothing is counted twice.

Laid out as a table with one row per die and one column per sum, each cell is the total of a k-wide strip of cells in the row above, just to its left. Row 0 has a single 1 at sum 0: no dice, total zero, one way.

Approach: Row-by-row DP over dice

  1. Start with dp[0] = 1 and every other sum 0: zero dice can only make 0.
  2. For each die i from 1 to n, build a fresh array nxt of length target + 1.
  3. For each sum s from 1 to target, set nxt[s] to the sum of dp[s - f] for f = 1..min(k, s), modulo 10^9 + 7.
  4. Replace dp with nxt.
  5. After all dice, return dp[target].

Step-by-step example

n = 2, k = 6, target = 7
  1. Row 0: dp = [1,0,0,0,0,0,0,0].
  2. Die 1: each sum 1..6 picks up the single 1 at sum 0, so row 1 is [0,1,1,1,1,1,1,0]. Sum 7 needs a face of 7, which does not exist.
  3. Die 2, sum 7: faces 1..6 point back to sums 6,5,4,3,2,1 of row 1, which are all 1.
  4. Adding them gives 6.
  5. The answer is 6: the pairs (1,6), (2,5), (3,4), (4,3), (5,2), (6,1).

Code: Python, Java, C++

1class Solution:
2    def numRollsToTarget(self, n: int, k: int, target: int) -> int:
3        MOD = 10**9 + 7
4        dp = [1] + [0] * target
5        for i in range(1, n + 1):
6            nxt = [0] * (target + 1)
7            for s in range(1, target + 1):
8                for f in range(1, min(k, s) + 1):
9                    nxt[s] = (nxt[s] + dp[s - f]) % MOD
10            dp = nxt
11        return dp[target]
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n * target * k)

Each of the n rows has target cells, and each cell adds up at most k values. With n, k <= 30 and target <= 1000 that is under a million additions.

Space

O(target)

Only the previous row and the row being built are kept.

Other approaches

Sliding window sum (time O(n * target), space O(target))

Each cell adds a k-wide strip of the row above, and the strip for s + 1 is the strip for s shifted by one. Keep a running window sum to fill each row in O(target).

Top-down memoization (time O(n * target * k), space O(n * target))

Recurse on (dice left, sum left), trying every face, and cache the results. Same recurrence, often easier to write first.

Common mistakes

  • Forgetting the modulo on each addition. The counts grow like k^n and overflow 32-bit integers long before the end.
  • Updating one array in place from left to right. The cells you read must come from the previous die, so build a new row (or loop sums downward).
  • Treating the dice as identical. Order matters here, which is exactly what summing over the last die's face counts.
  • Letting s - f go negative. Limit f to min(k, s).

Frequently asked questions

Why is dp[0][0] equal to 1?

There is exactly one way to roll zero dice: do nothing, which totals 0. Every real roll is built on top of that empty start, so it must count once.

Can the answer ever be 0?

Yes. If target is below n (each die shows at least 1) or above n * k (each die shows at most k), no roll can reach it.

How is this related to Coin Change II?

Both add up values to reach a target. Coin Change II counts combinations where order does not matter and coins can repeat freely, while here there is exactly one value per die and order matters, so the outer loop runs over dice.