LeetCode #377 Medium

Combination Sum IV

Combination Sum IV is LeetCode 377 (Medium). Given an array of distinct positive integers nums and a target, return how many sequences of numbers from nums add up to target.

  • A number may be used any number of times.
  • Order counts: (1, 2) and (2, 1) are two different sequences, despite the word "combination" in the name.
  • The answer fits in a 32-bit integer.

Only a count is asked for, and the target is at most 1000, so this is a counting DP, not a backtracking search.

Constraints
  • 1 <= nums.length <= 200
  • 1 <= nums[i] <= 1000
  • All the elements of nums are unique.
  • 1 <= target <= 1000
dynamic-programmingarray
Open on LeetCode ↗
02

Intuition

Look at the last number of a sequence. If a sequence adds up to t and ends with num, then what comes before it is a sequence adding up to t − num, and any such sequence plus num gives one ending in num. So:

ways(t) = sum of ways(t − num) over every num ≤ t, with ways(0) = 1 for the empty sequence.

Different last numbers give different sequences, so nothing is counted twice, and every sequence has some last number, so nothing is missed. Because the last number can be any of them, (1, 2) and (2, 1) land in different terms, which is exactly why order counts.

How to spot this pattern

"How many ways to reach a total" with unlimited use is a counting DP over the total. When order matters, the state is just the total; when it does not, you would also need to track which numbers are still allowed.

03

Approach

Try it first

Before reading on, write out the sequences for nums = [1, 2, 3] and target 4, grouped by their last number. How do the group sizes relate to the answers for totals 3, 2 and 1?

1

One cell per total

Make dp of size target + 1, where dp[t] will hold the number of ordered sequences adding up to t. Set dp[0] = 1: choosing nothing is the one way to reach 0, and every count is built on it.

2

Fill the totals from small to large

For t from 1 to target, add dp[t - num] for each num that is at most t. Every dp[t - num] is for a smaller total, so it is already final when it is read.

3

Keep the total loop outside

The loop over totals goes outside and the loop over numbers inside. That way, when dp[t] is filled, every number gets its turn as the last one, which is what counting ordered sequences needs.

4

Return the last cell

dp[target] is the answer. Python's integers never overflow; in C++ and Java, see the pitfall on overflow below.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def combinationSum4(self, nums: List[int], target: int) -> int:
▶3 dp = [0] * (target + 1)
▶4 dp[0] = 1
▶5 for t in range(1, target + 1):
▶6 for num in nums:
▶7 if num > t:
▶8 continue
▶9 dp[t] += dp[t - num]
▶10 return dp[target]
nums123101234ways to reach 01take nothing1 way to reach 0: take nothing
dp[0]1the empty sequence
target4
Each box on the line is a total from 0 to 4, and its number will be how many ordered sequences add up to it. Only total 0 is known at the start: the empty sequence is the one way to reach it, and every other count is built from it.
nums123+11011234ways to reach 11end 1=1end with 1: 1 way to reach 0 → total 1 has 1
dp[0]1ways to reach 0
dp[1]1
Every sequence for 0 becomes a sequence for 1 by adding 1 at the end. That gives 1 sequence for 1 that end in 1; none was counted before, since those end in a different number.
nums123+11011234ways to reach 11end 1=12 is bigger than 1 → skip
total1
num2
A sequence adding up to 1 cannot end with 2, because 2 alone is already more than 1. So no sequence for 1 is counted through it.
nums123+11011234ways to reach 11end 1=13 is bigger than 1 → skip
total1
num3
A sequence adding up to 1 cannot end with 3, because 3 alone is already more than 1. So no sequence for 1 is counted through it.
nums123+110111234ways to reach 21end 1=1end with 1: 1 way to reach 1 → total 2 has 1
dp[1]1ways to reach 1
dp[2]1
Every sequence for 1 becomes a sequence for 2 by adding 1 at the end. That gives 1 sequence for 2 that end in 1; none was counted before, since those end in a different number.
nums123+1+210112234ways to reach 21end 1+1end 2=2end with 2: 1 way to reach 0 → total 2 has 2
dp[0]1ways to reach 0
dp[2]2
Every sequence for 0 becomes a sequence for 2 by adding 2 at the end. That gives 1 sequence for 2 that end in 2; none was counted before, since those end in a different number.
nums123+1+210112234ways to reach 21end 1+1end 2=23 is bigger than 2 → skip
total2
num3
A sequence adding up to 2 cannot end with 3, because 3 alone is already more than 2. So no sequence for 2 is counted through it.
nums123+1101122234ways to reach 32end 1=2end with 1: 2 ways to reach 2 → total 3 has 2
dp[2]2ways to reach 2
dp[3]2
Every sequence for 2 becomes a sequence for 3 by adding 1 at the end. That gives 2 sequences for 3 that end in 1; none was counted before, since those end in a different number.
nums123+1+2101122334ways to reach 32end 1+1end 2=3end with 2: 1 way to reach 1 → total 3 has 3
dp[1]1ways to reach 1
dp[3]3
Every sequence for 1 becomes a sequence for 3 by adding 2 at the end. That gives 1 sequence for 3 that end in 2; none was counted before, since those end in a different number.
nums123+1+2+3101122434ways to reach 32end 1+1end 2+1end 3=4end with 3: 1 way to reach 0 → total 3 has 4
dp[0]1ways to reach 0
dp[3]4
Every sequence for 0 becomes a sequence for 3 by adding 3 at the end. That gives 1 sequence for 3 that end in 3; none was counted before, since those end in a different number.
nums123+11011224344ways to reach 44end 1=4end with 1: 4 ways to reach 3 → total 4 has 4
dp[3]4ways to reach 3
dp[4]4
Every sequence for 3 becomes a sequence for 4 by adding 1 at the end. That gives 4 sequences for 4 that end in 1; none was counted before, since those end in a different number.
nums123+1+21011224364ways to reach 44end 1+2end 2=6end with 2: 2 ways to reach 2 → total 4 has 6
dp[2]2ways to reach 2
dp[4]6
Every sequence for 2 becomes a sequence for 4 by adding 2 at the end. That gives 2 sequences for 4 that end in 2; none was counted before, since those end in a different number.
nums123+1+2+31011224374ways to reach 44end 1+2end 2+1end 3=7end with 3: 1 way to reach 1 → total 4 has 7
dp[1]1ways to reach 1
dp[4]7
Every sequence for 1 becomes a sequence for 4 by adding 3 at the end. That gives 1 sequence for 4 that end in 3; none was counted before, since those end in a different number.
nums123+1+2+31011224374ways to reach 44end 1+2end 2+1end 3=7answer: 7 sequences add up to 4
dp[4]7
Total 4 is filled, so the answer is 7. Grouped by their last number, the sequences are 4 ending in 1, 2 ending in 2, 1 ending in 3. Two sequences with the same numbers in a different order sit in different groups, so both count.
05

Common pitfalls

Putting the number loop outside

✗ Wrong
for num in nums:
    for t in range(num, target + 1):
        dp[t] += dp[t - num]
✓ Right
for t in range(1, target + 1):
    for num in nums:
        if num <= t:
            dp[t] += dp[t - num]

With numbers outside, all uses of 1 are added before any 2, so each sequence is only counted in sorted order. That is the Coin Change II count. For [1, 2, 3] and 4 it returns 4 instead of 7.

Signed int overflow in C++

✗ Wrong
vector<int> dp(target + 1, 0);
✓ Right
vector<unsigned int> dp(target + 1, 0);

Only the final answer is promised to fit. For nums = 10, 20, …, 990 plus 111 and target 999, the answer is 1 (nine 111s), yet dp[990] is 2^98. Signed overflow is undefined behaviour in C++, and the judge stops it with a runtime error. Unsigned values wrap around modulo 2^32 by rule, and since every step is an addition, the wrapped dp[target] equals the true answer modulo 2^32, which is the answer itself because it fits. Java's int wraps the same way, so it needs no change.

Backtracking over every sequence

✗ Wrong
def count(remain):
    if remain == 0: return 1
    return sum(count(remain - x) for x in nums if x <= remain)
✓ Right
@cache
def count(remain): ...

Without saving results, count(remain) is recomputed every time it is reached. For [1, 2, 3] and target 34 that is over a billion calls. Caching it gives the same O(target · n) as the table.

06

Edge cases

Every number is bigger than the target, e.g. nums = [9], target 3

No number ever fits, so every cell above 0 stays 0 and the answer is 0.

07

Complexity

Time
O(target · n)
Space
O(target)
Each of the target cells looks at all n numbers once. The table has target + 1 cells; no other memory grows with the input.
08

Combination Sum IV FAQ

How is it different from Combination Sum (39)?

Both allow reusing a number, but Combination Sum lists the sets of numbers, so [1, 2] and [2, 1] are one answer and backtracking is used. Here only a count is returned and the two orders count twice, so a DP replaces the search.

What if negative numbers were allowed?

Then the count can be infinite: with 1 and −1, you can add 1, −1 to any sequence as many times as you like. To make it finite you would have to cap the length of a sequence, and the state would become (total, length).

Is the top-down version just as good?

Yes. A memoized count(remain) gives the same answer in the same time, and only visits totals that are reachable. The table version avoids deep recursion, which matters in Python when the target is near 1000.