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
candidatesmay 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
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.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code