Combination Sum II
Detailed guide and Python implementation for the 'Combination Sum II' problem.
1. Concept Overview
The 'Combination Sum II' problem is a key challenge in the Backtracking section.
This implementation focuses on easy-level logic in Python.
We prioritize technical accuracy and code readability in our provided solutions.
2. Real-World Applications
3. Visual Intuition
Visualizing the logic flow for Combination Sum II.
4. Prerequisites
5. Step-by-Step Thinking
1. Understand the problem
Read the problem statement for Combination Sum II carefully.
2. Formulate brute force
Draft a simple iterative solution.
3. Identify inefficiency
Look for redundant calculations.
4. Optimize search path
Use hashing or sorting to speed up the process.
5. Final Implementation
Clean up the code for production standards.
Problem Statement
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.
Each number in candidates may only be used once in the combination.
Note: The solution set must not contain duplicate combinations.
Implement a function combinationSum2(candidates: list, target: int) -> list.
- •1 <= candidates.length <= 100
- •1 <= candidates[i] <= 50
- •1 <= target <= 30
Examples
[10,1,2,7,6,1,5], 8
[[1,1,6],[1,2,5],[1,7],[2,6]]
All unique combinations that sum to 8, using each element at most once.
[2,5,2,1,2], 5
[[1,2,2],[5]]
1+2+2 = 5 and 5 = 5. These are the only unique combinations.
Need a Hint?
Edge Cases to Watch
- Empty input structures
- Single element inputs
- Large numerical bounds
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.
Interview Insights & Variations
Complexity Analysis Breakdown
Why Time: Directly evaluates all possibilities.
Why Space: Uses standard local memory.
Why Time: Optimized paths reduce total operations.
Why Space: May trade memory for speed.
Optimized Solution Python Code
Optimized Solution Python Code
def combination_sum2_opt(candidates: list[int], target: int) -> list[list[int]]:
res = []
candidates.sort()
def backtrack(cur, pos, target):
if target == 0:
res.append(cur[:])
return
if target <= 0: return
prev = -1
for i in range(pos, len(candidates)):
if candidates[i] == prev: continue
cur.append(candidates[i])
backtrack(cur, i + 1, target - candidates[i])
cur.pop()
prev = candidates[i]
backtrack([], 0, target)
return resBrute Force Code (Spoiler Guarded)
Brute Force Code (Spoiler Guarded)
def combination_sum2_brute(candidates: list[int], target: int) -> list[list[int]]:
res = []
candidates.sort()
def dfs(i, cur, total):
if total == target:
if cur not in res: res.append(cur[:])
return
if total > target or i == len(candidates):
return
cur.append(candidates[i])
dfs(i + 1, cur, total + candidates[i])
cur.pop()
dfs(i + 1, cur, total)
dfs(0, [], 0)
return resAlgorithm Pattern Checklist
When dealing with Backtracking data patterns.
Core Prerequisites
Revision Key Notes
Common Mistakes & Pitfalls
Related Questions
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Loops
Learn how to use Python loops to iterate over data. Master for loops, while loops, break, continue, and loop best practices with interactive examples.
How to Sort a List in Python
Learn how to sort a list in Python using the sort() method and the sorted() function. Discover custom key sorting and reverse order examples.
Python String Methods
A complete reference guide for Python string manipulation. Master formatting, searching, splitting, replacing, and checking string properties.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.