Combination Sum (LeetCode 39): Solution and Explanation

Medium
Array
Backtracking

Given an array of distinct positive integers and a target, list every unique combination of candidates whose values add up to the target. Any candidate may be used as many times as you like, and two combinations count as the same if they contain the same numbers with the same multiplicities, regardless of order.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

A first instinct is to build sums by trying every candidate at every step. That finds all valid sums but produces duplicates such as [2,2,3], [2,3,2] and [3,2,2], because it treats order as meaningful. You would then have to sort and deduplicate, which wastes a lot of work.

The fix is to make choices in a fixed order so each combination can only be built one way. Walk through the candidates by index, and at each index make a single decision: either take candidates[i] one more time and stay at the same index, or decide you are finished with it and move to i + 1. Because you never go back to an earlier index, every combination is generated in non-decreasing index order exactly once.

This forms a binary decision tree. The left branch adds the current candidate and keeps the index, which is how unlimited reuse happens. The right branch moves past it for good. Since all candidates are positive, the running total only grows, so any branch whose total exceeds the target can be abandoned immediately, and any branch that hits the target exactly records a copy of the current combination.

Approach: Backtracking with include or skip decisions

  1. Create res for results and call dfs(0, [], 0), where the arguments are the current index, the current combination and its total.
  2. If total == target, append a copy of cur to res and return.
  3. If i is past the last candidate or total exceeds target, return because this branch cannot succeed.
  4. Include branch: append candidates[i] to cur and recurse with the same i and the larger total, so the same number can be used again.
  5. Pop it back off cur to undo the choice.
  6. Skip branch: recurse with i + 1 and the unchanged total, meaning this candidate is never used again on this path.

Step-by-step example

candidates = [2,3,6,7], target = 7
  1. Including 2 repeatedly builds [2], [2,2] and [2,2,2] with totals 2, 4 and 6. Adding a fourth 2 makes 8, which exceeds 7, so that branch stops.
  2. From [2,2,2], skipping to 3, 6 and 7 gives totals of 9, 12 and 13, all too large, and the index then runs out.
  3. Back at [2,2] with total 4, skipping 2 and including 3 gives a total of 7, so [2,2,3] is recorded.
  4. Other branches such as [2,3] (total 5) and [3,3] (total 6) cannot reach exactly 7 with the remaining larger candidates, so they all overshoot and stop.
  5. Skipping 2, 3 and 6 entirely and including 7 reaches 7, so [7] is recorded.
  6. The final result is [[2,2,3],[7]].

Code: Python, Java, C++

1class Solution:
2    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
3        res = []
4        
5        def dfs(i, cur, total):
6            if total == target:
7                res.append(cur.copy())
8                return
9            if i >= len(candidates) or total > target:
10                return
11            
12            cur.append(candidates[i])
13            dfs(i, cur, total + candidates[i])
14            cur.pop()
15            dfs(i + 1, cur, total)
16            
17        dfs(0, [], 0)
18        return res

Time and space complexity

Time

O(2^(n + t/m))

Here t is the target and m is the smallest candidate. Each step either adds a candidate, which can happen at most t/m times on a path, or advances the index, which can happen at most n times, so the binary decision tree has depth at most n + t/m. Copying each found combination adds a smaller extra cost.

Space

O(n + t/m)

The recursion depth and the length of cur are bounded by the same path length, ignoring the space used by the output itself.

Other approaches

Loop-based backtracking from a start index (time O(n^(t/m)), space O(t/m))

At each call, loop j from the current start to the end, add candidates[j], and recurse with start j. Sorting the candidates first lets you break out of the loop as soon as a value exceeds the remaining target. It explores the same combinations with a shallower tree.

Dynamic programming over sums (time O(n × t × C), space O(t × C))

Build a table where entry s holds every combination summing to s, processing candidates in the outer loop so each combination is formed in one order. It avoids recursion but stores many partial lists, which can use a lot of memory. Here C stands for the number of combinations kept per sum.

Common mistakes

  • Appending cur itself instead of cur.copy(). Later pops would then change the stored result.
  • Advancing to i + 1 on the include branch, which prevents a candidate from being reused.
  • Looping over all candidates from index 0 at every level, which generates the same combination in several orders.
  • Forgetting the total > target check, which leads to unbounded recursion along the include branch.

Frequently asked questions

How do you avoid duplicate combinations in Combination Sum?

Only move forward through the candidate list. Once you skip an index you never return to it, so each combination is built in a single canonical order and appears exactly once.

How is Combination Sum different from Combination Sum II?

Here each candidate can be reused without limit and all candidates are distinct. In the second version each number can be used once and the input may contain duplicates, so you sort and skip equal neighbors at the same depth.

Why does the include branch keep the same index?

Staying on the same index after taking a candidate lets you take it again on the next step. That is how the algorithm supports unlimited reuse without trying earlier candidates and creating reordered duplicates.