Given candidates that may contain duplicates and a target, return all unique combinations that sum to the target, using each candidate at most once.
Before you code
Two equal candidates at the same level of the search lead to identical branches. Generating everything and deduplicating at the end works, but wastes most of the time.
Hints
- Sort the candidates so equal values are adjacent.
- Recurse with
i + 1, because each candidate can be used once. - In the loop, skip
candidates[i]wheni > startand it equalscandidates[i - 1]: that value was already tried at this level. - Break once a candidate exceeds the remaining sum.
Production & complexity notes
When solving Combination sum II on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Backtracking basics to reinforce the underlying pattern.
What it practices
The choose, explore, unchoose pattern and pruning, from Backtracking basics.