Combination Sum II
Combination Sum II is LeetCode 40 (Medium). You get an array candidates that may contain duplicate values and a positive target. Return every unique combination of candidates that adds up to target.
- Each array element may be used at most once in a combination.
- Two combinations that hold the same values are the same answer, whatever order they are in, so the list must not contain one twice.
The target is at most 30, so a backtracking search that stops early stays small even with 100 candidates.
- 1 <= candidates.length <= 100
- 1 <= candidates[i] <= 50
- 1 <= target <= 30
Intuition
Sort the array, then build each combination from left to right, choosing one index per depth. Equal values now sit next to each other, which makes the repeats easy to see.
- Same depth, same value: if two equal values are both offered as the next choice, the second copy can only build lists the first copy already built. Skip a value that equals its left neighbour, unless it is the first option at this depth.
- Deeper down: the second copy may still be taken right after the first, so
[1, 1, 6]is still found.
The question wants every combination listed, not a count, so the answer is a search that builds lists and undoes choices. Duplicates in the input plus "no repeated combinations" is the signal for sort-then-skip.
Approach
Before reading on, sort [2, 1, 3, 1] and list the combinations that make 4 by hand. Which branch would build [1, 3] a second time, and what single comparison stops it?
Sort the candidates
Sort once at the start. It puts equal values side by side, so a repeat is found by comparing with the left neighbour, and it puts small values first, so the loop can stop at the first value that is too big.
Search with a start index
Write dfs(start, remain): try each index i from start to the end as the next number, with remain still to reach. Starting at start means the numbers in a combination always come in sorted order, so [1, 3] is never also built as [3, 1].
Skip repeats at the same depth
Inside the loop, skip i when i > start and candidates[i] == candidates[i - 1]. The i > start part keeps the first copy at each depth, so a second copy can still be used one depth further down, right after the first.
Stop early, record, and undo
If candidates[i] > remain, break: the array is sorted, so no later value fits either. Otherwise append it, call dfs(i + 1, remain - candidates[i]), then pop it. When remain reaches 0, save a copy of the path, since the list itself keeps changing.
Code in Python, C++ and Java
Common pitfalls
Comparing with the neighbour without the i > start guard
if i > 0 and candidates[i] == candidates[i - 1]:
continueif i > start and candidates[i] == candidates[i - 1]:
continueWith i > 0, the second 1 is skipped even when it is the first option one level down, right after taking the first 1. On [1, 1, 6] with target 8 the answer [1, 1, 6] is lost and nothing is returned. The mistake hides because it removes answers instead of adding repeats.
Recursing with i instead of i + 1
dfs(i, remain - candidates[i])
dfs(i + 1, remain - candidates[i])
Passing i lets the same element be taken again, which is the rule of Combination Sum (39). On [2] with target 4 it returns [[2, 2]] when the answer is [].
Removing repeats with a set afterwards
seen = set() # build every subset that sums to target, # then add tuple(path) to seen
if i > start and candidates[i] == candidates[i - 1]:
continueThe search still walks every repeated branch before the set throws the copies away. On thirty 1s with target 15, it builds over 150 million lists to keep a single one, [1] * 15; the skip builds just one.
Edge cases
[5, 6], target 3The first value already fails candidates[i] > remain, so the loop breaks at once and [] is returned.
Complexity
Combination Sum II FAQ
How is it different from Combination Sum (39)?
In Combination Sum the values are distinct and each can be reused, so the search recurses with i. Here each element is used once (recurse with i + 1) and equal values may repeat, so the same-depth skip is needed.
Why is skipping the second copy safe?
At one depth, both copies would become the same next number, and the indices after the second copy are a subset of the indices after the first. So any list built from the second copy can also be built from the first. Nothing is lost, only the repeat.
What if only the number of combinations is needed?
The same search can return a count instead of lists. With a target this small, a DP over (index, remaining sum) that treats each run of equal values as one group also works, choosing how many copies of the value to take.