Combination Sum II

Medium

Topics
ArrayBacktracking

Given candidates (which may contain duplicates) and a target, return all unique combinations summing to target. Each candidate may be used at most once.

Example 1

100112273641556
Input:  candidates = [10,1,2,7,6,1,5], target = 8
Output: [[1,1,6],[1,2,5],[1,7],[2,6]]

Example 2

2051221324
Input:  candidates = [2,5,2,1,2], target = 5
Output: [[1,2,2],[5]]

Constraints

  • 1 <= candidates.length <= 100
  • 1 <= candidates[i] <= 50
  • 1 <= target <= 30
Editorial — intuition, approach, complexity and pitfalls

Intuition

Like Combination Sum, but each item is used once and duplicates must not produce duplicate combinations. Sort, advance the index each pick, and skip equal values at the same depth.

Approach

  1. Sort candidates.
  2. DFS advancing to i+1 (each used once).
  3. Skip candidates[i] == candidates[i-1] when i > start to dedupe.

Dry Run

candidates [10,1,2,7,6,1,5] sorted to [1, 1, 2, 5, 6, 7, 10], target 8
answer [1,1,6] | [1,2,5] | [1,7] | [2,6]
This page needs both controls at once, and each one alone is wrong in its own way.
`dfs(i + 1, ...)` enforces single use. Recurse from `i` instead and the same
element is reusable, which is combination-sum's rule, not this one -- the output
balloons to ten results including [1,1,1,1,1,1,1,1] and [2,2,2,2].
`i > start` suppresses duplicate branches. Drop the skip entirely and the two 1s
each start their own branch at the top level, producing [1,2,5] and [1,7] twice:
six results instead of four, with two exact duplicates.
Change it to `i > 0` and it over-suppresses, exactly as in subsets-ii: [1,1,6]
vanishes, leaving only [1,2,5] [1,7] [2,6]. The combination that legitimately
USES both 1s is the casualty.
So: i + 1 controls how often one element may be used, and i > start controls how
often one VALUE may begin a branch. They are independent, and getting one right
does not cover the other.

Complexity

  • Time — O(2^n): subset exploration with pruning.
  • Space — O(n): recursion depth.

Common Pitfalls

  • Advance to i+1 (single use) and skip duplicates only at i > start.

Full Solution — all languages

class Solution:
    def combinationSum2(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 i>start and candidates[i]==candidates[i-1]: continue
                if candidates[i]>rem: break
                path.append(candidates[i]); dfs(i+1,rem-candidates[i],path); path.pop()
        dfs(0,target,[])
        return res
Asked at Snap
SensAI
Beta
Tap the mic to stop voice mode