Combination Sum II

medium

Given a collection of candidate numbers candidates and a target number target, find all unique combinations in candidates whose numbers add up to target.

Each number in candidates may be used at most once in a single combination. Note that candidates can contain duplicate values — so the same value may appear more than once in a combination, as long as it comes from different positions in the input.

The result must not contain duplicate combinations. Two combinations are considered the same when they use the same multiset of values, regardless of order — return each such handful only once.

Hints

You need every distinct handful that sums to the target — start by pinning down what makes two handfuls 'the same'.
Sort the numbers first. Now equal values are neighbours, and 'use each position once' just means always moving your index forward.
At each recursion level, skip a number identical to the one you just tried at that level, and recurse from i+1 so no position is reused.

Common doubts

Sorting groups equal values so the duplicate-skip rule candidates[i] == candidates[i-1] works, and it lets you prune the moment a value exceeds the remaining target.
There you recurse from i to reuse the same number; here you recurse from i+1 because each position may be used at most once, plus you skip sibling duplicates from the input.
The first candidate at each level (i == start) must always be tried — skipping it would drop valid combinations. Only later duplicates at the same level are redundant.

Interview follow-ups

Keep the same backtracking but increment a counter at each remaining == 0 instead of storing the combo — O(1) extra space beyond the recursion stack.
That becomes Combination Sum: recurse from i instead of i+1 and drop the sibling-duplicate skip (deduping input repeats up front instead).

Fun facts

  • The sort-then-skip-left-neighbour trick is the exact same one that powers Subsets II and Permutations II — learn it once, reuse it everywhere.
  • Because the values are positive, a single break on candidates[i] > remaining prunes whole subtrees for free — no separate bound check needed.

Asked at

AmazonMicrosoftGoogleAdobeBloomberg
Frequently Sometimes Occasionally
Example 1
Input: candidates = [10,1,2,7,6,1,5], target = 8
Output: [[1,1,6],[1,2,5],[1,7],[2,6]]
There are two 1s in the input, so 1 + 1 + 6 is allowed. Each combination sums to 8 and uses each chosen position once.
Example 2
Input: candidates = [2,5,2,1,2], target = 5
Output: [[1,2,2],[5]]
1 + 2 + 2 uses two of the three 2s; 5 stands alone. No handful is listed twice.
Constraints

- 1 <= candidates.length <= 100 - 1 <= candidates[i] <= 50 - 1 <= target <= 30

Solve this problem →