Combination Sum II

MediumBacktrackingLeetCode 40 ↗World 4-9
0:00 / 0:00

Find every combination that sums to a target, using each number once. Sort, skip repeats at the same depth, and stop once numbers get too big.

▼

The problem

LeetCode 40 (Medium). You get an array candidates, which may contain duplicates, and a target. Return all unique combinations of candidates that sum to the target. Each number may be used at most once in a combination, and the answer must not contain duplicate combinations.

Example (LeetCode's first): [10,1,2,7,6,1,5], target 8 → [[1,1,6],[1,2,5],[1,7],[2,6]].

TRY IT ON LEETCODE ▶

The solution

def combinationSum2(nums, target):
    nums.sort()
    out = []
    def go(start, due, picks):
        if due == 0:
            out.append(picks[:])
            return
        for i in range(start, len(nums)):
            if i > start and nums[i] == nums[i - 1]:
                continue
            if nums[i] > due:
                break
            picks.append(nums[i])
            go(i + 1, due - nums[i], picks)
            picks.pop()
    go(0, target, [])
    return out

Transcript

Combination Sum Two. You get numbers, some repeated, and a target. Return every unique combination summing to it. Each number is used at most once, and no combination may repeat.

Take ten, one, two, seven, six, one, five; target eight. A toll booth taking only exact change accepts one, one, six; one, two, five; one, seven; and two, six.

The slow way tries all a hundred and twenty-eight subsets. Six pay exactly eight. But with two ones, one, seven turns up twice, and so does one, two, five. A set drops the copies, but the work is wasted.

So sort first, and twins sit side by side. Build combinations from a start position. At each depth, if a coin equals the one before it, skip it: that value already had its turn. Once a coin is bigger than what's due, stop: the rest are bigger too. After a pick, continue from the next position, so each coin is used once.

Let's pay eight. One, then the second one: allowed, it's the first pick at this depth. Two leaves four, and five is too big: stop. Five leaves one. Six leaves nothing: save one, one, six. Back to a single one: one, two, five, save. One, five and one, six come up short. One, seven, save. At the top, the second one is a twin: skip. Two, six, save. Five, six and seven find nothing; ten's over eight. Four answers, no repeats, in seventeen calls.

In code, a helper takes the start, what's due, and the picks. When nothing is due, save a copy. Otherwise loop from start: skip twins after the first, break when a coin is too big, pick it, recurse from the next index, and pop it.

Worst case, nothing gets cut: every subset is reached and each answer copied, order two to the n times n time. The recursion takes order n space.

Sort, skip twins, stop early. That's Combination Sum Two.