Combination Sum II — LeetCode 40 Python Solution
- Problem
- #40
- Pattern
- Backtracking
- Reading time
- 4 min
- Source
- leetcode.com
The 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. Each number in candidates may only be used once in the combination.
Example
- Input
- candidates = [10,1,2,7,6,1,5], target = 8
- Output
- [
Python solution
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
def dfs(i: int, s: int):
if s == 0:
ans.append(t[:])
return
if i >= len(candidates) or s < candidates[i]:
return
for j in range(i, len(candidates)):
if j > i and candidates[j] == candidates[j - 1]:
continue
t.append(candidates[j])
dfs(j + 1, s - candidates[j])
t.pop()
candidates.sort()
ans = []
t = []
dfs(0, target)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(2^n \times n) |
| Space | O(n) auxiliary |
Pattern: Backtracking
Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 40. Combination Sum II is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Backtracking.
The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.
Related problems
On a study list
This problem is on NeetCode 150.
Frequently asked questions
- How hard is LeetCode 40. Combination Sum II?
- LeetCode 40. Combination Sum II is rated Medium on LeetCode.
- What is the time complexity of LeetCode 40. Combination Sum II?
- The Python solution on this page runs in O(2^n \times n).
- What is the space complexity of LeetCode 40. Combination Sum II?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 40. Combination Sum II cover?
- LeetCode 40. Combination Sum II is tagged Array and Backtracking on LeetCode.