Combination Sum II - Problem

Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target.

Important constraints:

  • Each number in candidates may only be used once in the combination
  • The solution set must not contain duplicate combinations

Return the answer as a list of lists, where each inner list represents a valid combination.

Input & Output

Example 1 — Basic Case with Duplicates
$ Input: candidates = [10,1,2,7,6,1,5], target = 8
Output: [[1,1,6],[1,2,5],[1,7],[2,6]]
💡 Note: After sorting [1,1,2,5,6,7,10], we find combinations: 1+1+6=8, 1+2+5=8, 1+7=8, and 2+6=8. Each number is used at most once per combination.
Example 2 — Multiple Duplicates
$ Input: candidates = [2,5,2,1,2], target = 5
Output: [[1,2,2],[5]]
💡 Note: After sorting [1,2,2,2,5], valid combinations are: 1+2+2=5 (using first two 2s) and 5=5. The combination [2,2,1] would be duplicate of [1,2,2].
Example 3 — No Valid Combinations
$ Input: candidates = [1,2], target = 4
Output: []
💡 Note: No combination of [1,2] can sum to 4. Maximum possible sum is 1+2=3.

Constraints

  • 1 ≤ candidates.length ≤ 100
  • 1 ≤ candidates[i] ≤ 50
  • 1 ≤ target ≤ 30

Visualization

Tap to expand
Combination Sum II INPUT candidates array: 10 1 2 7 6 1 5 Sorted: 1 1 2 5 6 7 10 target = 8 8 ALGORITHM STEPS 1 Sort Array Enable duplicate skipping 2 Backtrack Try each element once 3 Skip Duplicates If same as previous, skip 4 Prune Branches Stop if sum exceeds target Decision Tree (partial): [] [1] [2] [1,1] [1,2] FINAL RESULT 4 Unique Combinations Found: [1, 1, 6] 1 + 1 + 6 = 8 [1, 2, 5] 1 + 2 + 5 = 8 [1, 7] 1 + 7 = 8 [2, 6] 2 + 6 = 8 Output: [[1,1,6], [1,2,5], [1,7], [2,6]] Key Insight: Sort the array first to group duplicates together. During backtracking, skip an element if it's the same as the previous one at the same recursion level. This prevents duplicate combinations while allowing the same value to appear in different positions within a single combination. TutorialsPoint - Combination Sum II | Optimal Backtracking Approach
Asked in
Amazon 45 Microsoft 38 Google 35 Facebook 28
89.2K Views
High Frequency
~25 min Avg. Time
3.2K 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