-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcombination_sumII.py
More file actions
36 lines (30 loc) · 1.08 KB
/
combination_sumII.py
File metadata and controls
36 lines (30 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution(object):
def combinationSum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
candidates.sort() # Sort to handle duplicates easily
res = []
def backtrack(start, path, remaining):
if remaining == 0:
res.append(list(path))
return
if remaining < 0:
return
prev = -1
for i in range(start, len(candidates)):
# Skip duplicates (only skip if same as previous on same level)
if candidates[i] == prev:
continue
# Stop if number exceeds remaining target (since sorted)
if candidates[i] > remaining:
break
# Choose current number
path.append(candidates[i])
backtrack(i + 1, path, remaining - candidates[i])
path.pop()
prev = candidates[i]
backtrack(0, [], target)
return res