Skip to content

Commit 364f101

Browse files
committed
Combination Sum II
1 parent ae9740d commit 364f101

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

Backtracking/40-Combination-Sum-II.py

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
'''Leetcode- https://leetcode.com/problems/combination-sum-ii/'''
2+
'''
3+
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.
4+
5+
Each number in candidates may only be used once in the combination.
6+
7+
Note: The solution set must not contain duplicate combinations.
8+
9+
Example 1:
10+
11+
Input: candidates = [10,1,2,7,6,1,5], target = 8
12+
Output:
13+
[
14+
[1,1,6],
15+
[1,2,5],
16+
[1,7],
17+
[2,6]
18+
]
19+
'''
20+
21+
22+
def combinationSum2(candidates, target):
23+
candidates.sort()
24+
res = []
25+
26+
def backtrack(cur, pos, target):
27+
if target == 0:
28+
res.append(cur.copy())
29+
if target <= 0:
30+
return
31+
prev = -1
32+
for i in range(pos, len(candidates)):
33+
if candidates[i] == prev:
34+
continue
35+
cur.append(candidates[i])
36+
backtrack(cur, i+1, target-candidates[i])
37+
cur.pop()
38+
prev = candidates[i]
39+
40+
backtrack([], 0, target)
41+
return res
42+
43+
#T:O(2^n)
44+
#S:O(n)

README.md

+2
Original file line numberDiff line numberDiff line change
@@ -14,4 +14,6 @@ Check the notes for the explaination - [Notes](https://stingy-shallot-4ea.notion
1414
- [x] [Permutations II](Backtracking/47-Permutations-II.py)
1515
- [x] [Combinations](Backtracking/77-Combinations.py)
1616
- [x] [Combination Sum](Backtracking/39-Combination-Sum.py)
17+
- [x] [Combination Sum II](Backtracking/40-Combination-Sum-II.py)
18+
1719

0 commit comments

Comments
 (0)