sagelearnai

Combination Sum

Difficulty: Medium · Pattern: Backtracking · LeetCode #39

Given distinct positive integers candidates and a positive target, return all unique combinations of candidates that sum to target. Each candidate may be used any number of times. Two combinations are the same if they use the same numbers with the same counts. Any order is fine.

Examples

text
candidates = [2, 3, 6, 7], target = 7   →  [[2, 2, 3], [7]]
candidates = [2, 3, 5], target = 8      →  [[2,2,2,2], [2,3,3], [3,5]]
candidates = [2], target = 1            →  []

Hints

  1. To avoid generating [2, 3] and [3, 2] separately, only pick candidates at index ≥ the last one picked.
  2. Since reuse is allowed, recurse with the same index after picking.
  3. Sort the candidates so you can stop early once a candidate exceeds the remaining target.

Approach

Sort the candidates. bt(start, remaining): if remaining == 0, record the path. Otherwise for i ≥ start: if candidates[i] > remaining, break (all later ones are larger too); else append it and recurse with bt(i, remaining − candidates[i]). Passing i (not i + 1) allows reuse, and never going below start prevents permuted duplicates.

Complexity

Time: exponential, roughly O(N^(T/M)) for N candidates, target T and smallest candidate M. Space: O(T/M) recursion depth.

Python solution
def combinationSum(candidates, target):
    candidates.sort()
    res, path = [], []
    def bt(start, remaining):
        if remaining == 0:
            res.append(path[:])
            return
        for i in range(start, len(candidates)):
            c = candidates[i]
            if c > remaining:
                break
            path.append(c)
            bt(i, remaining - c)
            path.pop()
    bt(0, target)
    return res
JavaScript solution
function combinationSum(candidates, target) {
  candidates.sort((a, b) => a - b);
  const res = [], path = [];
  const bt = (start, remaining) => {
    if (remaining === 0) { res.push([...path]); return; }
    for (let i = start; i < candidates.length; i++) {
      const c = candidates[i];
      if (c > remaining) break;
      path.push(c);
      bt(i, remaining - c);
      path.pop();
    }
  };
  bt(0, target);
  return res;
}