15% off all plans & roadmaps Use code
See plansCombination Sum IV
- LeetCode 377
- Medium
- Dynamic Programming (DP) Patterns
- 1D Array (Coin Change / Unbounded Knapsack Style)
Updated
TL;DR: Count the ordered sequences of numbers from nums that add up to target. Fill a table where each sum is built from the sums that sit one number earlier, for O(target * n) time.
Problem
You get an array of distinct integers nums and an integer target. Return the number of possible combinations that add up to target. The tests are generated so the answer fits in a 32-bit integer.
Example 1
Input: nums = [1,2,3], target = 4 Output: 7 Explanation: The possible combinations are: - (1, 1, 1, 1) - (1, 1, 2) - (1, 2, 1) - (1, 3) - (2, 1, 1) - (2, 2) - (3, 1) Different sequences count as different combinations.
Example 2
Input: nums = [9], target = 3 Output: 0
Constraints
1 <= nums.length <= 2001 <= nums[i] <= 1000- All the elements of
numsare unique. 1 <= target <= 1000
Constraints that matter
- target up to 1000 and n up to 200 means about 200,000 table updates. O(target * n) passes easily, while O(n^target) does not.
- Every value is at least 1, so each step moves the sum forward. The table only reads smaller indexes, so it can be filled in order with no cycles.
- The final answer fits in 32 bits, but counts for other sums may not. A 64-bit accumulator keeps the arithmetic safe in every language.
- Values are unique and order matters. You must count sequences, not sets, so the sum loop has to be the outer loop.
Hints
Hint 1
This is a one-dimensional DP over sums, the same shape as Coin Change and unbounded knapsack.
Hint 2
Count the ways to reach a remaining amount by trying every number as the next pick.
Solution
Intuition
This is a one-dimensional DP over sums, the same shape as Coin Change and unbounded knapsack. The answer for a sum is built from answers for smaller sums. Every number can be reused any number of times, which is what makes the knapsack unbounded.
Picture a staircase where landing s is the sum s, and each value in nums is a step size you may climb any number of times. The table is a row of landing counts, dp[s] holds how many step orders reach landing s, and steps taller than s are skipped.
Look at the last number in any valid sequence. It is some value x from nums, and the numbers before it must add up to target minus x. So the count for a sum s equals the sum of the counts for s minus x, over every x that fits.
Order matters here. Each x is a different last element, so (1, 2) and (2, 1) come from different parents and both count. Distinct values keep these groups disjoint, so no sequence is counted twice. Filling sums from 0 upward makes every smaller count ready before you need it.
Worked example
Input: nums = [1, 2, 3], target = 4 Output: 7 Explanation: There are seven ordered sequences that sum to 4. Order matters, so (1, 2, 1) and (2, 1, 1) are two separate answers. The dry runs below use this input.
Approach 1: Brute force recursion
Count the ways to reach a remaining amount by trying every number as the next pick. Pick a number, subtract it, and count the ways to finish what is left. When the remainder is exactly 0, that path is one valid sequence.
This is the true naive method. It explores every ordered path, so the same remainder is solved again on many branches. The work grows with the number of paths, not with the number of distinct sums.
Steps
- Define ways(remaining) that returns the number of ordered sequences reaching remaining.
- If remaining is 0, return 1. The empty sequence reaches it.
- Start a total at 0. For each num in nums, if num is at most remaining, add ways(remaining - num).
- Return the total.
- Call ways(target) and return the result.
Dry run
Trace on nums = [1, 2, 3] and target = 4. Here ways(r) is the count for remainder r.
- ways(0) = 1, the empty sequence.
- ways(1) = ways(0) = 1, since only 1 fits.
- ways(2) = ways(1) + ways(0) = 1 + 1 = 2.
- ways(3) = ways(2) + ways(1) + ways(0) = 2 + 1 + 1 = 4.
- ways(4) = ways(3) + ways(2) + ways(1) = 4 + 2 + 1 = 7.
The output is 7. Note that ways(2) is needed by ways(3) and again by ways(4). The naive tree solves it twice, and larger targets repeat far more work.
Complexity
| Time | O(n^T) |
|---|---|
| Space | O(T) |
Let n be the length of nums and T be the target. Each call makes at most n recursive calls, and each call subtracts at least 1, so the recursion depth is at most T. The number of root-to-leaf paths is at most n^T, so the total work is O(n^T) when n is at least 2. The call stack holds at most T frames at once, which gives O(T) extra space.
PythonTested in our runner
from typing import List, Optional
class Solution:
def combinationSum4(self, nums: List[int], target: int) -> int:
def ways(remaining: int) -> int:
# one empty sequence finishes an exact match
if remaining == 0:
return 1
total = 0
for num in nums:
if num <= remaining:
total += ways(remaining - num)
return total
return ways(target)JavaTested in our runner
import java.util.*;
class Solution {
public int combinationSum4(int[] nums, int target) {
return (int) ways(nums, target);
}
private long ways(int[] nums, int remaining) {
if (remaining == 0) return 1;
long total = 0;
for (int num : nums) {
if (num <= remaining) total += ways(nums, remaining - num);
}
return total;
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
int combinationSum4(vector<int>& nums, int target) {
return (int) ways(nums, target);
}
private:
unsigned long long ways(const vector<int>& nums, int remaining) {
if (remaining == 0) return 1;
unsigned long long total = 0;
for (int num : nums) {
if (num <= remaining) total += ways(nums, remaining - num);
}
return total;
}
};JavaScriptTested in our runner
var combinationSum4 = function(nums, target) {
const ways = (remaining) => {
if (remaining === 0) return 1;
let total = 0;
for (const num of nums) {
if (num <= remaining) total += ways(remaining - num);
}
return total;
};
return ways(target);
};GoTested in our runner
func combinationSum4(nums []int, target int) int {
var ways func(remaining int) int
ways = func(remaining int) int {
if remaining == 0 {
return 1
}
total := 0
for _, num := range nums {
if num <= remaining {
total += ways(remaining - num)
}
}
return total
}
return ways(target)
}C#Tested in our runner
public class Solution {
public int combinationSum4(int[] nums, int target) {
return (int) Ways(nums, target);
}
private long Ways(int[] nums, int remaining) {
if (remaining == 0) return 1;
long total = 0;
foreach (int num in nums) {
if (num <= remaining) total += Ways(nums, remaining - num);
}
return total;
}
}The 1D Array (Coin Change / Unbounded Knapsack Style) infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
1D Array (Coin Change / Unbounded Knapsack Style)
Approach 2: Bottom-up DP tableOptimal1D Array (Coin Change / Unbounded Knapsack Style)
What's slow in the previous approach is that small remainders get solved over and over. The insight that fixes it is to flip the direction. Solve sums from 0 upward and store each count in a table, so each sum is computed exactly once.
Each entry dp[s] equals the sum of dp[s - x] over every x in nums with x at most s. The entries for smaller sums already exist when you need them. The answer is the entry at index target.
Steps
- Create dp with target + 1 slots, all set to 0.
- Set dp[0] = 1, which counts the empty sequence.
- For s from 1 to target, loop over every num in nums.
- If num is larger than s, skip it.
- Otherwise add dp[s - num] to dp[s].
- Return dp[target].
Dry run
Start with dp = [1, 0, 0, 0, 0]. Each row below is one update. A skipped row means the number is larger than the current sum.
| Step | s | num | Update | dp after step |
|---|---|---|---|---|
| 0 | - | - | start | [1, 0, 0, 0, 0] |
| 1 | 1 | 1 | dp[1] += dp[0] = 1 | [1, 1, 0, 0, 0] |
| 2 | 1 | 2, 3 | skipped, larger than 1 | [1, 1, 0, 0, 0] |
| 3 | 2 | 1 | dp[2] += dp[1] = 1 | [1, 1, 1, 0, 0] |
| 4 | 2 | 2 | dp[2] += dp[0] = 1, now 2 | [1, 1, 2, 0, 0] |
| 5 | 2 | 3 | skipped, larger than 2 | [1, 1, 2, 0, 0] |
| 6 | 3 | 1 | dp[3] += dp[2] = 2 | [1, 1, 2, 2, 0] |
| 7 | 3 | 2 | dp[3] += dp[1] = 1, now 3 | [1, 1, 2, 3, 0] |
| 8 | 3 | 3 | dp[3] += dp[0] = 1, now 4 | [1, 1, 2, 4, 0] |
| 9 | 4 | 1 | dp[4] += dp[3] = 4 | [1, 1, 2, 4, 4] |
| 10 | 4 | 2 | dp[4] += dp[2] = 2, now 6 | [1, 1, 2, 4, 6] |
| 11 | 4 | 3 | dp[4] += dp[1] = 1, now 7 | [1, 1, 2, 4, 7] |
The last row leaves dp[4] = 7, which is the output.
Complexity
| Time | O(T * n) |
|---|---|
| Space | O(T) |
Let T be target and n be the length of nums. The outer loop runs T times, and the inner loop runs n times on each pass, so there are T * n updates. Each update is one addition, which takes constant time. The table holds T + 1 numbers, so the extra space is O(T).
PythonTested in our runner
from typing import List, Optional
class Solution:
def combinationSum4(self, nums: List[int], target: int) -> int:
# dp[s] is the number of ordered sequences that sum to s
dp = [0] * (target + 1)
dp[0] = 1
for s in range(1, target + 1):
for num in nums:
if num <= s:
dp[s] += dp[s - num]
return dp[target]JavaTested in our runner
import java.util.*;
class Solution {
public int combinationSum4(int[] nums, int target) {
// dp[s] is the number of ordered sequences that sum to s
long[] dp = new long[target + 1];
dp[0] = 1;
for (int s = 1; s <= target; s++) {
for (int num : nums) {
if (num <= s) dp[s] += dp[s - num];
}
}
return (int) dp[target];
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
int combinationSum4(vector<int>& nums, int target) {
// dp[s] is the number of ordered sequences that sum to s
// unsigned avoids undefined behaviour when intermediate counts grow large
vector<unsigned long long> dp(target + 1, 0);
dp[0] = 1;
for (int s = 1; s <= target; ++s) {
for (int num : nums) {
if (num <= s) dp[s] += dp[s - num];
}
}
return (int) dp[target];
}
};JavaScriptTested in our runner
var combinationSum4 = function(nums, target) {
// dp[s] is the number of ordered sequences that sum to s
const dp = new Array(target + 1).fill(0);
dp[0] = 1;
for (let s = 1; s <= target; s++) {
for (const num of nums) {
if (num <= s) dp[s] += dp[s - num];
}
}
return dp[target];
};GoTested in our runner
func combinationSum4(nums []int, target int) int {
// dp[s] is the number of ordered sequences that sum to s
dp := make([]int, target+1)
dp[0] = 1
for s := 1; s <= target; s++ {
for _, num := range nums {
if num <= s {
dp[s] += dp[s-num]
}
}
}
return dp[target]
}C#Tested in our runner
public class Solution {
public int combinationSum4(int[] nums, int target) {
// dp[s] is the number of ordered sequences that sum to s
long[] dp = new long[target + 1];
dp[0] = 1;
for (int s = 1; s <= target; s++) {
foreach (int num in nums) {
if (num <= s) dp[s] += dp[s - num];
}
}
return (int) dp[target];
}
}Common mistakes
- Swapping the loops, so
for num in numswraps the sum loop. That counts unordered sets, and for nums = [1, 2, 3] and target = 4 it returns 4 instead of 7. Keep the sum loop outside so each new sum sees every possible last pick. - Leaving out the
num <= scheck. In Python,dp[s - num]with a negative index reads from the end of the list and adds a wrong value without an error. Java and C++ crash or read garbage. Guard every access. - Setting
dp[0] = 0. Every nonzero count traces back to dp[0], so the whole table stays 0. The base case must be 1 for the empty sequence. - Sizing the table as
targetinstead oftarget + 1. The indextargetis then out of range. Allocate target + 1 slots so indexes 0 through target all exist. - Using a signed 32-bit accumulator in C++ or Java. Counts for other sums can pass 2^31, and signed overflow in C++ is undefined behaviour. Use a 64-bit type for the table and cast the final value back to int.
Edge cases
- target smaller than every value, with nums = [9] and target = 3. No sequence fits, so the answer is 0.
- A single value equal to target, with nums = [5] and target = 5. There is exactly one sequence, so the answer is 1.
- Only 1 in nums, with nums = [1] and target = 1000. The only sequence is 1000 ones, so the answer is 1.
- Order matters, with nums = [1, 2] and target = 3. The sequences are (1, 1, 1), (1, 2), and (2, 1), so the answer is 3.
- Maximum size, with 200 values and target = 1000. The table does about 200,000 updates, and the answer still fits in 32 bits by the constraints.
Follow-ups interviewers ask
- What if negative numbers are allowed in nums? How does that change the problem?
- The count can become infinite. With nums = [1, -1] and target = 0, you can add 1 and then -1 forever, so there are endless sequences. A zero in nums has the same effect. To make the problem well defined, cap the sequence length at L. Then the table needs a length dimension, and you can roll it forward one length at a time. The sum index also ranges below zero, so the table needs an offset.
- Can you reduce the space below O(target)?
- Yes, when target is larger than the biggest value. dp[s] only reads entries up to max(nums) places back, so a ring buffer of max(nums) + 1 slots is enough. The space becomes O(max(nums)) and the time stays O(T * n). If target is smaller than max(nums), the full table is already small.
- What if target is very large, such as 10^9?
- The table is far too big. The recurrence dp[s] = sum of dp[s - x] has an order equal to max(nums), so you can write it as a matrix of that size. Raising the matrix to the target power with fast exponentiation takes O(m^3 log T) time, where m is max(nums). The answer is usually taken modulo a prime in that setting, because it grows too fast to store.
Combination Sum IV FAQ
What is the time complexity of Combination Sum IV?
The bottom-up DP runs in O(target * n) time, where n is the length of nums. The plain recursion is O(n^target) in the worst case. Write the table version in an interview, and mention the recursion as the starting point.
Why use dynamic programming for Combination Sum IV?
Each sum's count depends only on counts for smaller sums. The same smaller sums repeat across many different paths. Dynamic programming stores each one once, so the repeated work disappears.
Can Combination Sum IV be solved in O(1) extra space?
No, not in general. The count for each sum depends on up to max(nums) earlier counts, so those counts must be stored. A ring buffer brings the space down to O(max(nums)), but it cannot reach O(1) for arbitrary inputs.
What is the difference between Combination Sum IV and Coin Change II?
Combination Sum IV counts ordered sequences, so the sum loop goes on the outside. Coin Change II counts unordered sets, so the coin loop goes on the outside. The same input can give different answers, so the loop order decides the problem.
Why does my Python solution return a wrong answer when I skip the num <= s check?
Python allows negative list indexes. When s - num is below 0, dp[s - num] reads from the end of the list and adds a meaningless value. No error is raised, so the answer is silently wrong. Keep the check.
Asked at
See which companies ask this — Pro
Related problems
- Coin Change · same technique: 1D Array (Coin Change / Unbounded Knapsack Style)
- Coin Change II · same technique: 1D Array (Coin Change / Unbounded Knapsack Style)
- Perfect Squares · same technique: 1D Array (Coin Change / Unbounded Knapsack Style)
- Distinct Subsequences · next harder, same pattern
- Maximum Subarray · same pattern: Dynamic Programming (DP) Patterns
- Word Break · same pattern: Dynamic Programming (DP) Patterns
- Longest Increasing Subsequence · same pattern: Dynamic Programming (DP) Patterns
- Edit Distance · same pattern: Dynamic Programming (DP) Patterns
- House Robber · same pattern: Dynamic Programming (DP) Patterns
- Longest Common Subsequence · same pattern: Dynamic Programming (DP) Patterns