Combination Sum II - Problem

You're given a collection of candidate numbers and a target number. Your mission is to find all unique combinations where the candidates sum exactly to the target.

Key constraints:

  • Each number in candidates may only be used once per combination
  • The solution set must not contain duplicate combinations
  • The same number may appear multiple times in the input array

Example: If candidates = [10,1,2,7,6,1,5] and target = 8, valid combinations include [1,1,6], [1,2,5], [1,7], and [2,6].

This is a classic backtracking problem that tests your ability to explore all possible combinations while avoiding duplicates efficiently.

Input & Output

example_1.py โ€” Basic Case
$ Input: candidates = [10,1,2,7,6,1,5], target = 8
โ€บ Output: [[1,1,6],[1,2,5],[1,7],[2,6]]
๐Ÿ’ก Note: These are all unique combinations that sum to 8. Note that [1,1,6] uses both 1's from the array, and we avoid duplicates like having [1,7] appear twice.
example_2.py โ€” No Solution
$ Input: candidates = [2,5,2,1,2], target = 5
โ€บ Output: [[1,2,2],[5]]
๐Ÿ’ก Note: We can form 5 using [5] directly, or combining [1,2,2]. Note that [2,2,1] is the same as [1,2,2] so we only include one.
example_3.py โ€” Single Element
$ Input: candidates = [2], target = 1
โ€บ Output: []
๐Ÿ’ก Note: No combination can sum to 1 since our only candidate is 2, which is greater than the target.

Constraints

  • 1 โ‰ค candidates.length โ‰ค 100
  • 1 โ‰ค candidates[i] โ‰ค 50
  • 1 โ‰ค target โ‰ค 30
  • Each number in candidates may only be used once in the combination
  • All values in candidates are positive integers

Visualization

Tap to expand
Backtracking Decision TreeTarget: 8, Candidates: [1,1,2,5,6,7,10]Start+1Skip+1+2+2+5[1,1] โ†’ sum=2[1,2] โ†’ sum=3[2] โ†’ sum=2[5] โ†’ sum=5Valid Solutions Found:[1,1,6][1,2,5][1,7][2,6]๐Ÿšซ Pruned branches: [1,1,7], [10], [1,1,2,5] (sum > 8)
Understanding the Visualization
1
Sort the Coins
Arrange candidates in ascending order: [1,1,2,5,6,7,10]
2
Start Building Combinations
At each level, decide whether to include the current coin
3
Skip Duplicates
When we see the same coin value at the same level, skip it to avoid duplicate combinations
4
Prune Invalid Paths
If current sum exceeds target, stop exploring this branch
5
Collect Valid Solutions
When sum equals target, add the combination to results
Key Takeaway
๐ŸŽฏ Key Insight: Sorting enables systematic duplicate avoidance while backtracking explores all valid paths efficiently through early pruning.
Asked in
Amazon 45 Google 38 Microsoft 32 Meta 28 Apple 22
89.2K Views
High Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen