SDE & MLE Prep

40. Combination Sum II

Problem

candidates may contain duplicates. Return every unique combination that sums to target, using each array element at most once, with no duplicate combinations.

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

Constraints: up to 100 candidates; target ≤ 30.

Each number used once (i + 1) and the input has duplicates → sort and skip equal neighbours at the same depth.

Complexity: O(2ⁿ).

class Solution:
    def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
        candidates.sort()
        res, path = [], []

        def bt(start, rest):
            if rest == 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] > rest:
                    break
                path.append(candidates[i])
                bt(i + 1, rest - candidates[i])
                path.pop()

        bt(0, target)
        return res