← Whiteboard questions

Combination Sum II

Find every way to reach a target using each number once

DSA, Medium, Backtracking

Which structure or algorithm, and what does it cost.

A list candidates of positive whole numbers may repeat a value. Return every distinct combination whose numbers add up to target. Each position of the list may be used at most once. Two combinations are the same if they hold the same values the same number of times. Write each one in increasing order. List them in any order. If there is none, return an empty list.

Examples

Input candidates = [3, 1, 3, 5, 2], target = 6
Output [[1, 2, 3], [1, 5], [3, 3]]
Why [1, 2, 3] is found once although either 3 can be used, and [3, 3] uses both 3s.
Input candidates = [4, 4, 4], target = 8
Output [[4, 4]]
Why two of the three 4s make 8, and that combination counts once.
Input candidates = [6, 7], target = 5
Output []
Why every number is too large, so the answer is empty.

Constraints

Your answer must contain

Target Aim to stop a branch once it passes the target, and never build the same combination twice.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

A position can be used only once, so after you take one number, the next choices come only from later positions. What about equal values?

Hint 2 the approach

Sort the list. If two equal numbers are both options at the same step, what do their branches produce?

Hint 3 the key step

Loop from a start position. Stop at a number above the remaining target. Skip a repeat of its neighbour unless first in the loop. Recurse from the next position.

Walkthrough

Full walkthrough brute force to best

Brute force

Look at every subset of the positions, which is 2^n subsets. Keep those whose sum is the target. Sort each one and put it in a set to drop repeats. The cost is O(n * 2^n), and most subsets are far over the target.

Best method

Sort the numbers. Keep the current combination, the remaining target and a start position. When the remaining target is 0, record a copy. Otherwise loop from the start position. Stop at the first number larger than the remaining target, because the later ones are larger still. Skip a number that equals the one before it unless it is the first number of this loop. Otherwise add it, call again from the next position, and remove it. The skip rule stops two equal numbers from starting the same combination at one step. Two equal numbers can still be used together, because the second one is not the first of the deeper loop.

Hand trace

Run on [3, 1, 3, 5, 2] with target 6. Sorted, the list is [1, 2, 3, 3, 5]. Take 1 (left 5), then 2 (left 3), then 3 (left 0) and record [1, 2, 3]. The next 3 repeats in this loop, so skip it. 5 is more than 3, so stop. Back at [1], take 3 (left 2): the next number is 3, more than 2, so stop. Skip the second 3. Take 5 (left 0) and record [1, 5]. At the top, take 2 (left 4), then 3 (left 1): stop. Skip the second 3. 5 is more than 4, so stop. Take 3 (left 3), then the second 3 (left 0) and record [3, 3]. 5 is more than 3, so stop. Skip the second 3. Take 5 (left 1): nothing follows. The result is [[1, 2, 3], [1, 5], [3, 3]].

Code

def combination_sum_once(candidates, target):
    nums = sorted(candidates)
    out = []
    path = []
    def go(start, left):
        if left == 0:
            out.append(path[:])
            return
        for i in range(start, len(nums)):
            if nums[i] > left:
                break
            if i > start and nums[i] == nums[i - 1]:
                continue
            path.append(nums[i])
            go(i + 1, left - nums[i])
            path.pop()
    go(0, target)
    return out

Time and memory

O(n * 2^n) time in the worst case: each position is taken or left, and a record copies up to n numbers. Extra memory is O(n) for the current combination and the call stack, plus the answer.

Common mistakes

  • Recursing from the same position. That lets one number be used again, but each position may be used once.
  • Skipping a number whenever it equals the one before it. Then [3, 3] is lost. Skip only when it is not the first of the loop.
  • Not sorting first. Equal numbers are then not neighbours, so the skip test misses them.

Related problems

More Backtracking problems
Combination Sum II: hints, walkthrough and Python solution