Combination Sum IV (LeetCode 377): Solution and Explanation
Given distinct positive integers nums and a target, count the ordered sequences of numbers from nums (with repetition) that sum to target. Despite the name, order matters: (1, 2) and (2, 1) are two different answers.
Intuition
Listing every sequence is hopeless: the count grows exponentially with the target. But the sequences have a simple structure you can count without listing them.
Look at the last number of any sequence that sums to i. If it is num, then everything before it is a sequence that sums to i - num, and any such sequence works. So the sequences ending in num are exactly the sequences for i - num, each with num appended.
Every sequence has exactly one last number, so these groups do not overlap and together cover everything. That gives dp[i] = dp[i - num1] + dp[i - num2] + ... over every num <= i.
The base case is dp[0] = 1: the empty sequence is the single way to make 0, and it is what a one-number sequence like (3) is built from.
This looks like Coin Change II, but there the loops are swapped. Looping over totals on the outside lets every number be the last one at every total, which counts each ordering separately. Looping over numbers on the outside would fix the order and count each multiset once.
Approach: 1D DP over the total
- Create
dpof sizetarget + 1filled with 0, and setdp[0] = 1. - For each
totalfrom 1 totarget: - For each
numinnumswithnum <= total, adddp[total - num]todp[total]. - Return
dp[target].
Step-by-step example
nums = [1,2,3], target = 4
dp[0] = 1for the empty sequence.dp[1] = dp[0] = 1: just (1).dp[2] = dp[1] + dp[0] = 2: (1,1) and (2).dp[3] = dp[2] + dp[1] + dp[0] = 2 + 1 + 1 = 4: (1,1,1), (2,1) end in 1, (1,2) ends in 2, and (3) ends in 3.dp[4] = dp[3] + dp[2] + dp[1] = 4 + 2 + 1 = 7: append 1 to the four sequences for 3, 2 to the two for 2, and 3 to the one for 1.- The answer is 7.
Code: Python, Java, C++
1class Solution:
2 def combinationSum4(self, nums: List[int], target: int) -> int:
3 dp = [0] * (target + 1)
4 dp[0] = 1 # one way to make 0: pick nothing
5 for total in range(1, target + 1):
6 for num in nums:
7 if num <= total:
8 dp[total] += dp[total - num]
9 return dp[target]1class Solution {
2 public int combinationSum4(int[] nums, int target) {
3 int[] dp = new int[target + 1];
4 dp[0] = 1; // one way to make 0: pick nothing
5 for (int total = 1; total <= target; total++) {
6 for (int num : nums) {
7 if (num <= total) {
8 dp[total] += dp[total - num];
9 }
10 }
11 }
12 return dp[target];
13 }
14}1class Solution {
2public:
3 int combinationSum4(vector<int>& nums, int target) {
4 // unsigned: sums that never reach the answer may overflow harmlessly
5 vector<unsigned int> dp(target + 1, 0);
6 dp[0] = 1; // one way to make 0: pick nothing
7 for (int total = 1; total <= target; total++) {
8 for (int num : nums) {
9 if (num <= total) {
10 dp[total] += dp[total - num];
11 }
12 }
13 }
14 return dp[target];
15 }
16};Time and space complexity
O(target * n)
Each of the target totals looks at each of the n numbers once.
O(target)
One array of target + 1 counts.
Other approaches
Top-down recursion with memo (time O(target * n), space O(target))
count(r) returns 1 when r == 0, otherwise the sum of count(r - num) for num <= r, cached by r. It computes the same values but only for remainders reachable from target.
Plain backtracking (time O(n^target), space O(target))
Try every number at every step and count the paths that land exactly on the target. Correct but exponential, so it times out long before target = 1000.
Common mistakes
- Swapping the loops (numbers outside, totals inside). That counts combinations without order, which is Coin Change II, and gives 4 instead of 7 on the first example.
- Forgetting
dp[0] = 1. Without it every entry stays 0. - Integer overflow in C++. Entries for totals that never feed the target can exceed 32 bits even though the answer fits. Signed overflow is undefined behavior in C++, so use
unsigned int(wraparound is defined and the final answer is still exact). - Assuming the answer is monotonic in the target. With
nums = [2, 3],dp[1]is 0 whiledp[2]anddp[3]are 1.
Frequently asked questions
Why is it called Combination Sum if order matters?
It is the name of the series on LeetCode. This problem's statement says explicitly that different sequences count as different combinations, so it is really counting compositions, not combinations.
What changes if nums can contain negative numbers?
Then the count can be infinite, because a positive and a negative number can cancel out forever, for example 1 + (-1) + 1 + (-1) + ... You would have to cap the length of a sequence, which adds a length dimension to the DP.
Why can intermediate values overflow if the answer fits?
The guarantee is only about dp[target]. A total that cannot reach the target, for example one smaller than the target by an amount no number in nums can make up, can still have a huge count, and it is computed anyway.