Combination Sum

Medium

Topics
ArrayBacktracking

Given distinct positive integers candidates and a target, return all unique combinations that sum to target. A candidate may be reused unlimited times.

Example 1

20316273
Input:  candidates = [2,3,6,7], target = 7
Output: [[2,2,3],[7]]

Example 2

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

Constraints

  • 1 <= candidates.length <= 30
  • All candidates are distinct positive integers.
  • 1 <= target <= 40
Editorial — intuition, approach, complexity and pitfalls

Intuition

Explore combinations by choosing candidates in non-decreasing index order (so each combination is generated once), subtracting from the remaining target and allowing reuse of the current index.

Approach

  1. DFS with (start index, remaining).
  2. When remaining hits 0, record the path; if it goes negative, prune.
  3. Recurse with the same index i (reuse) to allow repeats.

Dry Run

candidates [2, 3, 6, 7] (sorted), target 7
`rem` counts down; reaching exactly 0 records the path.
  take 2  rem 5   path [2]        recurse from i=0, so 2 may repeat
    take 2  rem 3   path [2,2]    recurse from i=0
      take 2  rem 1   path [2,2,2]
        2 > rem 1 -- sorted, so every later candidate is too: BREAK
      take 3  rem 0   path [2,2,3]  ->  record
      6 > rem 3: BREAK
    take 3  rem 2   path [2,3]
      3 > rem 2: BREAK
    6 > rem 5: BREAK
  take 3  rem 4   path [3]
    take 3  rem 1   path [3,3]
      3 > rem 1: BREAK
    6 > rem 4: BREAK
  take 6  rem 1   path [6]
    6 > rem 1: BREAK
  take 7  rem 0   path [7]  ->  record
answer [2, 2, 3] and [7]
Two uses of the sort, doing different jobs. `break` rather than `continue` is
valid only because the candidates ascend -- once one exceeds rem, so does every
candidate after it, which prunes the whole tail in one step. And recursing from
`i` rather than `i + 1` is what permits reuse: [2,2,3] needs the 2 twice. The
start index never moving backwards is separately what stops [3,2,2] being emitted
as a second copy of the same multiset.
Pass i + 1 instead and reuse is forbidden: the answer drops to just [[7]], since
no single-use subset of [2,3,6] sums to 7.

Complexity

  • Time — O(2^t): exponential in target/candidate ratio; pruned by the break.
  • Space — O(target): recursion depth.

Common Pitfalls

  • Recurse with i (not i+1) to permit reuse; pass i+1 and you forbid repeats.

Full Solution — all languages

class Solution:
    def combinationSum(self, candidates, target):
        candidates.sort()
        res=[]
        def dfs(start,rem,path):
            if rem==0: res.append(path[:]); return
            for i in range(start,len(candidates)):
                if candidates[i]>rem: break
                path.append(candidates[i]); dfs(i,rem-candidates[i],path); path.pop()
        dfs(0,target,[])
        return res
SensAI
Beta
Tap the mic to stop voice mode