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.
- 1 <= nums.length <= 200
- 1 <= nums[i] <= 1000
- All the elements of nums are unique.
- 1 <= target <= 1000
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 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.
Approach
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?
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.
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.
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.
Return the last cell
dp[target] is the answer. Python's integers never overflow; in C++ and Java, see the pitfall on overflow below.
Code in Python, C++ and Java
Common pitfalls
Putting the number loop outside
for num in nums:
for t in range(num, target + 1):
dp[t] += dp[t - num]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++
vector<int> dp(target + 1, 0);
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
def count(remain):
if remain == 0: return 1
return sum(count(remain - x) for x in nums if x <= remain)@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.
Edge cases
nums = [9], target 3No number ever fits, so every cell above 0 stays 0 and the answer is 0.
Complexity
target cells looks at all n numbers once. The table has target + 1 cells; no other memory grows with the input.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.