SDE & MLE Prep

39. Combination Sum

Problem

candidates are distinct positive integers. Return every unique combination that sums to target, where each candidate may be used any number of times. Two combinations differ if some number is used a different number of times.

Example: candidates = [2,3,6,7], target = 7 → [[2,2,3],[7]]

Constraints: up to 30 candidates; target ≤ 40.

Unlimited reuse → recurse with the same i. Sorting lets us break as soon as a candidate exceeds the remainder.

Complexity: exponential, bounded by O(n^(target/min)).

class Solution:
    def combinationSum(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)):
                c = candidates[i]
                if c > rest:
                    break
                path.append(c)
                bt(i, rest - c)          # i: same number may be reused
                path.pop()

        bt(0, target)
        return res