Skip to content

Combination Sum

MediumLeetCode #39Time O(N^(T/M))Space O(T/M)

You get an array of distinct positive integers and a target. Return every unique combination of those numbers that sums to the target. You may use the same number any number of times. Two combinations are the same if they use the same counts of each number.

candidates = [2, 3, 6, 7], target = 7 -> [[2, 2, 3], [7]]

Think of a tree where each step picks a number and subtracts it from the target. A branch ends when the remaining value hits 0 (record it) or goes negative (dead end).

Two details make it correct:

  • Reuse: recurse with i, not i + 1, so the same number can be picked again.
  • No duplicates: the loop starts at start, never earlier. So you can pick 2 then 3, but never 3 then 2. Each combination is built in one fixed order.

Sorting the candidates adds a cheap prune: once candidates[i] > remaining, every later number is bigger too, so break out of the loop.

Show solutionHide solution
def combination_sum(candidates: list[int], target: int) -> list[list[int]]:
candidates = sorted(candidates) # sorted lets us stop early
res, path = [], []
def backtrack(start: int, remaining: int) -> None:
if remaining == 0:
res.append(path[:])
return
for i in range(start, len(candidates)):
if candidates[i] > remaining:
break # prune: this and every later number is too big
path.append(candidates[i]) # choose
backtrack(i, remaining - candidates[i]) # explore: i, not i + 1, allows reuse
path.pop() # un-choose
backtrack(0, target)
return res
  • Time: O(N^(T/M)) — N candidates, target T, smallest candidate M. The tree is at most T/M deep with up to N branches per level. This is a loose upper bound; pruning and the start index make real runs much smaller. Copying each answer adds a factor of up to T/M.
  • Space: O(T/M) — recursion depth and path hold at most T/M numbers (all the smallest candidate). The output is not counted.
  • i, not i + 1, for the recursive call. Using i + 1 solves a different problem (each number used once).
  • Don’t restart the loop at 0. That generates [2, 3, 2], [3, 2, 2] and [2, 2, 3] as three separate answers.
  • Subtract as you go. Passing remaining is cheaper and clearer than re-summing the path.

Candidates may repeat, and each can be used once. Answers must be unique. The trick: sort, recurse with i + 1, and skip a value when i > start and it equals the previous one. That removes duplicate combinations at the same level.

Choose exactly k distinct numbers from 1 to 9 that sum to n. The trick: same template with i + 1, recording only when the path has k numbers and the sum is n. Stop early when the path is already too long.

Count (not list) the ways to make an amount from coins with unlimited reuse. The trick: backtracking is too slow. The same “loop coins outermost, allow reuse” order becomes a 1-D DP over amounts, which is also why combinations don’t count orderings twice.