CodingNodes / Backtracking / Combination Sum II System design Space play · ←→ step · R restart

Problem

You are given an array candidates of positive integers, which may contain repeated values, and a number target. Return every group of numbers from candidates whose sum is exactly target.

Each position of candidates can be used at most once. The answer must not contain the same group twice, even if equal numbers appear at different positions. The groups may be returned in any order.

Constraints

  • 1 ≤ candidates.length ≤ 100
  • 1 ≤ candidates[i] ≤ 50
  • 1 ≤ target ≤ 30

Examples: pick one to animate

Solutions

TimeO(2^n) SpaceO(n)

Time: Each position is either taken or left out, so there are at most 2^n groups to look at. Sorting adds O(n log n), which is smaller.

Space: Besides the output, the path and the recursion are at most n deep.

Sort first so equal numbers are neighbours. Recurse with i + 1 so a position is used once. Inside one loop, if candidates[i] equals the previous number and i is not the first choice of this loop, skip it: that group was already built. Because the list is sorted, a number that is too big ends the loop.