sagelearnai

Combination Sum II

Difficulty: Medium · Pattern: Backtracking · LeetCode #40

Find all unique combinations of candidates that sum to target. Each number may be used once, and candidates can contain duplicates. Any order is accepted.

Examples

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

Hints

  1. It's Subsets II with a sum constraint: same sort + skip-equal-siblings trick, recursing with i + 1.
  2. Because the array is sorted, once candidates[i] > remaining you can break. Every later number is bigger.

Approach

text
sort(c)
bt(start, rem):
    if rem == 0: record path
    for i in start..n-1:
        if i > start and c[i] == c[i-1]: continue   # dedupe
        if c[i] > rem: break                         # prune (sorted)
        path.push(c[i]); bt(i + 1, rem - c[i]); path.pop()

Compare with Combination Sum I, where reuse is allowed and you recurse with i instead of i + 1, with no dedupe because the candidates are distinct. Getting these two small differences right is what the interviewer is checking.

Complexity

Time: O(2ⁿ · n) worst case. Space: O(n).

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