-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCombinationSumII.py
More file actions
32 lines (30 loc) · 1.09 KB
/
CombinationSumII.py
File metadata and controls
32 lines (30 loc) · 1.09 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
class Solution(object):
def combinationSum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
candidates.sort()
result = self.recursive(candidates, 0, target)
for item in result:
item.reverse()
return result
def recursive(self, candidates, index, target):
if index >= len(candidates): return []
if candidates[index] == target:
return [[candidates[index]]]
elif candidates[index] > target:
return []
else:
result = []
for i in range(index, len(candidates)):
if i > index and candidates[i] == candidates[i- 1]: continue
if target - candidates[i] == 0:
result += [[candidates[i]]]
break
ret = self.recursive(candidates, i + 1, target - candidates[i])
for item in ret:
item.append(candidates[i])
result += ret
return result