15% off all plans & roadmaps Use code

See plans

Combination Sum IV

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 <= 200
  • 1 <= nums[i] <= 1000
  • All the elements of nums are 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.

View on LeetCode

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.

Watch the pattern animation

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

  1. Define ways(remaining) that returns the number of ordered sequences reaching remaining.
  2. If remaining is 0, return 1. The empty sequence reaches it.
  3. Start a total at 0. For each num in nums, if num is at most remaining, add ways(remaining - num).
  4. Return the total.
  5. 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

TimeO(n^T)
SpaceO(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)

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 infographic

Solution pattern

1D Array (Coin Change / Unbounded Knapsack Style)

Part of Dynamic Programming (DP) Patterns

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

  1. Create dp with target + 1 slots, all set to 0.
  2. Set dp[0] = 1, which counts the empty sequence.
  3. For s from 1 to target, loop over every num in nums.
  4. If num is larger than s, skip it.
  5. Otherwise add dp[s - num] to dp[s].
  6. 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.

StepsnumUpdatedp after step
0--start[1, 0, 0, 0, 0]
111dp[1] += dp[0] = 1[1, 1, 0, 0, 0]
212, 3skipped, larger than 1[1, 1, 0, 0, 0]
321dp[2] += dp[1] = 1[1, 1, 1, 0, 0]
422dp[2] += dp[0] = 1, now 2[1, 1, 2, 0, 0]
523skipped, larger than 2[1, 1, 2, 0, 0]
631dp[3] += dp[2] = 2[1, 1, 2, 2, 0]
732dp[3] += dp[1] = 1, now 3[1, 1, 2, 3, 0]
833dp[3] += dp[0] = 1, now 4[1, 1, 2, 4, 0]
941dp[4] += dp[3] = 4[1, 1, 2, 4, 4]
1042dp[4] += dp[2] = 2, now 6[1, 1, 2, 4, 6]
1143dp[4] += dp[1] = 1, now 7[1, 1, 2, 4, 7]

The last row leaves dp[4] = 7, which is the output.

Complexity

TimeO(T * n)
SpaceO(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]

Common mistakes

  • Swapping the loops, so for num in nums wraps 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 <= s check. 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 target instead of target + 1. The index target is 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

Practise it