15% off all plans & roadmaps Use code

See plans

Combination Sum

Updated

TL;DR: Find every multiset of distinct numbers, each reusable any number of times, that adds up to the target. Backtracking with a start index builds each combination in non-decreasing index order, so no duplicates appear, and sorting lets you stop a loop early.

Problem

You are given an array candidates of distinct integers and an integer target. Return a list of all unique combinations of candidates whose chosen numbers add up to target. The combinations may be returned in any order.

You may use the same number from candidates as many times as you like. Two combinations are different if at least one number appears a different number of times in them.

The tests are built so that the number of unique combinations summing to target is less than 150 for every input.

Example 1

Input: candidates = [2,3,6,7], target = 7
Output: [[2,2,3],[7]]
Explanation: 2 + 2 + 3 = 7, and 2 is used twice. Also 7 = 7. These are the only two combinations.

Example 2

Input: candidates = [2,3,5], target = 8
Output: [[2,2,2,2],[2,3,3],[3,5]]

Example 3

Input: candidates = [2], target = 1
Output: []

Constraints

  • 1 <= candidates.length <= 30
  • 2 <= candidates[i] <= 40
  • All elements of candidates are distinct.
  • 1 <= target <= 40

Constraints that matter

  • target <= 40 and candidates[i] >= 2 cap the length of any combination at 20 numbers. That keeps recursion depth tiny, so recursion is safe in every language.
  • Fewer than 150 answers are guaranteed. Output size is small, so the cost is dominated by how many dead-end branches you explore, and pruning is what matters.
  • All values are positive. The running sum only grows, so once it passes target you can abandon that branch for good. With zero or negative values this would not hold.
  • Candidates are distinct. You never need to skip equal neighbours to avoid duplicate answers, which is the main difference from Combination Sum II.
  • candidates.length <= 30 rules out any approach that tries all 2^30 subsets blindly, but it does not rule out a pruned search.

View on LeetCode

Hints

Hint 1

This is backtracking.

Hint 2

Walk through the candidates in order and, for each one, decide how many copies to include, from the maximum that fits down to zero.

Solution

Intuition

This is backtracking. You build an answer one number at a time, check whether you hit the target, and undo the last choice to try the next one. The search tree has one level per number added, and the positive values let you cut any branch whose sum already exceeds target.

It is like shopping from a price list sorted cheapest to most expensive with a fixed budget. The sorted array is the price list, the remaining sum rem is what is left in your wallet, and the break is the moment you stop reading because the current item already costs more than you have.

The detail that decides everything is how to avoid counting [2, 2, 3] and [2, 3, 2] as two answers. The fix is to impose an order. After you pick candidates[i], you may pick candidates[i] again or anything to its right, but never anything to its left. Each multiset then has exactly one path in the tree, the one that lists its numbers in index order.

Reuse comes from passing i instead of i + 1 into the recursive call. Duplicate prevention comes from starting the loop at start instead of 0. Those two small choices are the whole algorithm.

Sorting adds one more cut. If candidates is sorted ascending and candidates[i] is already larger than the remaining sum, every later candidate is larger too. You can break out of the loop instead of testing each one.

Watch the pattern animation

Worked example

Input: candidates = [2, 3, 6, 7], target = 7
Output: [[2, 2, 3], [7]]
Explanation: Using 2 twice and 3 once gives 2 + 2 + 3 = 7. Using 7 once gives 7. Every other mix, such as 2 + 2 + 2 + 1 or 3 + 3 + 1, either overshoots or cannot hit 7 exactly. Order inside a combination does not matter, so [2, 3, 2] is the same answer as [2, 2, 3].

Approach 1: Brute force: choose a count for every candidate

Walk through the candidates in order and, for each one, decide how many copies to include, from the maximum that fits down to zero. At the end of the list, check whether the remaining sum is exactly zero. Every multiset is produced once because each candidate gets one count, so no deduplication step is needed.

This is the plain "try every option" search. It does not use any ordering trick beyond the fixed candidate order, and it keeps descending to the end of the array even when nothing is left to place.

Steps

  1. Define choose(i, rem, path) where i is the candidate being decided and rem is the sum still needed.
  2. If rem == 0, record a copy of path and return, since all later candidates must get count zero.
  3. If i equals the number of candidates, return, because rem is still positive and nothing is left to add.
  4. Let c = candidates[i]. For k from rem / c down to 0, append k copies of c to path.
  5. Recurse with choose(i + 1, rem - k * c).
  6. Remove the k copies you added, then try the next smaller k.
  7. Call choose(0, target) and return the recorded list.

Dry run

Candidates [2, 3, 6, 7], target 7. Counts are tried from high to low.

  • Candidate 2 can appear up to 3 times. Take k=3, path [2,2,2], rem 1. Candidates 3, 6, 7 all get count 0, the list ends with rem 1, so this branch fails.
  • Take k=2, path [2,2], rem 3. Candidate 3 with k=1 gives [2,2,3] and rem 0, so it is recorded. Candidate 3 with k=0 leaves rem 3, and 6 and 7 cannot fill it.
  • Take k=1, path [2], rem 5. Candidate 3 with k=1 leaves rem 2, and 3 with k=0 leaves rem 5. Neither can be finished by 6 or 7.
  • Take k=0, path [], rem 7. Candidate 3 can reach rem 1 or 4, which fail. Candidate 6 leaves rem 1, which fails. Candidate 7 with k=1 gives rem 0, so [7] is recorded.

Result: [[2,2,3],[7]].

Complexity

TimeO(product over i of (T / candidates[i] + 1)) upper bound
SpaceO(n + T / m) excluding the output

Let n be the number of candidates, T the target and m the smallest candidate. Each candidate has at most T / candidates[i] + 1 count choices, and the tree multiplies those choices, so the product bounds the leaf count. Sum pruning keeps the real count far lower. Recursion depth is n and the path holds at most T / m numbers, which gives the space bound.

PythonTested in our runner

from typing import List

class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        result = []
        path = []
        n = len(candidates)

        def choose(i: int, rem: int) -> None:
            if rem == 0:
                result.append(path[:])
                return
            if i == n:
                return
            c = candidates[i]
            for k in range(rem // c, -1, -1):
                path.extend([c] * k)
                choose(i + 1, rem - k * c)
                del path[len(path) - k:]

        choose(0, target)
        return result

Approach 2: Backtracking with a start index

What's slow in the count-choice search: it descends one level per candidate, even for candidates that cannot fit. A branch with rem 1 still walks through 6, 7 and the end of the array before failing. Most of the tree is chains of count-zero choices that add nothing.

The insight that fixes it is to recurse on the combination itself. Loop over candidates from start, append one, and recurse with the same index i so it can be reused. Depth now equals the number of numbers in the combination, not the number of candidates, and each node does real work: it adds one number.

Steps

  1. Define backtrack(start, rem) with a shared path list.
  2. If rem == 0, record a copy of path and return.
  3. Loop i from start to the last index.
  4. If candidates[i] > rem, skip it with continue.
  5. Append candidates[i] to path and call backtrack(i, rem - candidates[i]). Passing i allows reuse and forbids going left.
  6. Pop the last number to undo the choice.
  7. Call backtrack(0, target) and return the result.

Dry run

Candidates [2, 3, 6, 7], target 7, unsorted order is the same as sorted here.

  • Root, rem 7: take 2, path [2], rem 5. Take 2 again, path [2,2], rem 3. Take 2 again, path [2,2,2], rem 1. Every candidate is larger than 1, so the loop skips all four and returns.
  • Back at [2,2], rem 3: take 3, path [2,2,3], rem 0, recorded. Candidates 6 and 7 are skipped.
  • Back at [2], rem 5: take 3, path [2,3], rem 2. Everything is too big. 6 and 7 are skipped too.
  • Root: take 3, path [3], rem 4, then [3,3] rem 1 with nothing fitting. 6 and 7 are skipped at rem 4.
  • Root: 6 gives rem 1 with nothing fitting. 7 gives rem 0, so [7] is recorded.

Result: [[2,2,3],[7]]. The loop still tests each too-large candidate once per node.

Complexity

TimeO(n^(T / m)) upper bound
SpaceO(T / m) excluding the output

Let n be the number of candidates, T the target and m the smallest candidate. Every number added is at least m, so the recursion depth is at most T / m, and each node loops over at most n candidates. That gives at most n^(T / m) nodes as a loose bound, and each recorded answer costs O(T / m) to copy. The stack and the path both hold at most T / m entries.

PythonTested in our runner

from typing import List

class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        result = []
        path = []

        def backtrack(start: int, rem: int) -> None:
            if rem == 0:
                result.append(path[:])
                return
            for i in range(start, len(candidates)):
                c = candidates[i]
                if c > rem:
                    continue
                path.append(c)
                backtrack(i, rem - c)  # i, not i + 1: reuse is allowed
                path.pop()

        backtrack(0, target)
        return result
Combination Sum pattern infographic for Combination Sum

Solution pattern

Combination Sum

Part of Backtracking Patterns

Approach 3: Sort, then backtrack with early breakOptimalCombination Sum

What's slow in the start-index version: at every node the loop still looks at each candidate to its right, including the ones that are too large. If the candidates are in arbitrary order, you must test every one with continue.

The insight that fixes it is to sort candidates ascending first. Once candidates[i] > rem, every later candidate is at least as large, so none can fit. Replace continue with break and the loop ends at the first failure.

Sorting costs O(n log n) once and saves scanning work at every node. Answers also come out in a predictable order.

Steps

  1. Sort a copy of candidates in ascending order.
  2. Define backtrack(start, rem) with a shared path list.
  3. If rem == 0, record a copy of path and return.
  4. Loop i from start to the end of the sorted array.
  5. If nums[i] > rem, break. Every later value is larger, so nothing else fits.
  6. Append nums[i], recurse with backtrack(i, rem - nums[i]), then pop.
  7. Call backtrack(0, target) and return the result.

Dry run

The table traces sorted candidates [2, 3, 6, 7] with target 7. rem is the sum still needed when the call starts.

SteppathremAction
1[]7i=0, take 2
2[2]5i=0, take 2
3[2,2]3i=0, take 2
4[2,2,2]12 > 1, break, return
5[2,2]3i=1, take 3
6[2,2,3]0record [2,2,3], return
7[2,2]3i=2, 6 > 3, break, return
8[2]5i=1, take 3, path [2,3], rem 2
9[2,3]23 > 2, break, return
10[2]5i=2, 6 > 5, break, return
11[]7i=1, take 3, path [3], rem 4
12[3]4i=1, take 3, path [3,3], rem 1; then 3 > 1, break
13[3]4i=2, 6 > 4, break, return
14[]7i=2, take 6, path [6], rem 1; then 6 > 1, break
15[]7i=3, take 7, path [7], rem 0, record [7]

The recorded answers are [2,2,3] and [7], so the output is [[2,2,3],[7]]. Step 4 ends the loop after one comparison instead of four.

Complexity

TimeO(n^(T / m)) upper bound
SpaceO(T / m) excluding the output

Let n be the number of candidates, T the target and m the smallest candidate. Sorting costs O(n log n), which is tiny next to the search. Depth is at most T / m because every pick is at least m, and each node loops over at most n values, so n^(T / m) bounds the node count.

The break only shrinks the loop at each node, so the bound stays the same but the work in practice drops. Space is the recursion stack plus the path, both at most T / m.

PythonTested in our runner

from typing import List

class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        nums = sorted(candidates)
        result = []
        path = []

        def backtrack(start: int, rem: int) -> None:
            if rem == 0:
                result.append(path[:])
                return
            for i in range(start, len(nums)):
                if nums[i] > rem:
                    break  # sorted, so every later value is too big as well
                path.append(nums[i])
                backtrack(i, rem - nums[i])
                path.pop()

        backtrack(0, target)
        return result

Common mistakes

  • Calling backtrack(0, rem - c) inside the loop. Every level restarts from the first candidate, so [2,3] and [3,2] both appear. Pass i so the search never moves left.
  • Calling backtrack(i + 1, rem - c). That forbids reuse, so [2,2,3] is never found. Pass i, not i + 1, to let the same number repeat.
  • Storing result.append(path) or result.add(path) without a copy. The path keeps changing, so every stored answer ends up empty. Store path[:], new ArrayList<>(path) or a fresh array.
  • Using break on an unsorted array. A large value early in the list would stop the loop before smaller values to its right are tried, and valid answers vanish. Sort first, or use continue instead.
  • Forgetting to undo the choice after the recursive call, such as a missing path.pop(). The next sibling then sees leftover numbers and builds wrong combinations. Every push needs a matching pop.
  • In Java and C#, returning a List<List<Integer>> when the signature is int[][]. Convert each recorded path to an int[] and the outer list to an array.

Edge cases

  • candidates = [2], target = 1: no combination exists, so return an empty list.
  • candidates = [7], target = 7: one candidate equals the target, so return [[7]].
  • candidates = [2], target = 40: the only answer is twenty 2s. Recursion depth reaches 20, which is fine.
  • candidates = [3, 2, 7, 6] in unsorted order: the answer set is the same as for [2, 3, 6, 7]. Only the order of the answers may differ.
  • Target smaller than every candidate, such as [5, 6], target 4: the loop skips or breaks immediately and the result is empty.
  • 30 distinct candidates with target = 40: depth is small and pruning keeps the search fast, but the result list must still hold fewer than 150 combinations.

Follow-ups interviewers ask

What changes if candidates may contain duplicates and each element can be used only once (Combination Sum II)?
Sort the array, recurse with i + 1 so each element is used once, and skip a value when it equals the previous value at the same loop level. The skip stops two equal siblings from starting the same subtree and producing duplicate answers.
What if you only need the number of combinations, not the combinations themselves?
Use dynamic programming. Keep ways[s] as the count of multisets summing to s, set ways[0] = 1, and for each candidate in the outer loop update ways[s] += ways[s - c] for s from c to the target. That runs in O(n * T) time and O(T) space. Putting candidates in the outer loop counts each multiset once instead of counting orderings.
What if candidates could be zero or negative?
The search no longer terminates, because the running sum can stay at or below the target forever. A zero adds infinitely many answers by repeating it. You would need an explicit cap on combination length, and the early break on nums[i] > rem is no longer valid.

Combination Sum FAQ

What is the time complexity of Combination Sum?

It is O(n^(T / m)) as an upper bound, where n is the number of candidates, T the target and m the smallest candidate. The tree has depth at most T / m and each node branches at most n ways. Pruning and the guarantee of fewer than 150 answers make real runs much cheaper than this bound. Space is O(T / m) beyond the output.

Why use backtracking for Combination Sum?

You must list every valid combination, not count them, so you have to build each one explicitly. Backtracking builds one candidate answer at a time, checks it, and undoes the last pick to try another. Because all numbers are positive, you can cut a branch as soon as the sum exceeds the target.

How do I solve the Combination Sum problem on LeetCode?

Sort the candidates, then run a recursive function with a start index and the remaining sum. Add a number, recurse with the same index so it can repeat, and pop it afterwards. Record the path when the remaining sum hits zero, and break when the next candidate is larger than what remains.

What is combination sum?

It is the task of finding all multisets drawn from a list of numbers that add up to a given target. In LeetCode 39 each number can be reused any number of times, and two combinations are the same if they use each number equally often. Order inside a combination does not matter.

Can Combination Sum be solved in O(1) extra space?

No. You need a path that holds up to T / m numbers and a recursion stack of the same depth, where T is the target and m the smallest candidate. An iterative version replaces the stack with an explicit one but still stores the path. The output list is not counted as extra space.

Why does my Python solution return a list of empty lists?

You appended the shared path object, not a copy. Backtracking pops from it until it is empty, and every stored reference shows that final state. Use result.append(path[:]) or list(path).

What is the difference between Combination Sum and Combination Sum II?

In Combination Sum numbers are distinct and reusable, so you recurse with i. In Combination Sum II the list may hold duplicates and each element is used once, so you sort, recurse with i + 1, and skip equal neighbours at the same depth.

Asked at

See which companies ask this — Pro

Practise it