-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path040.py
More file actions
48 lines (44 loc) · 1.37 KB
/
040.py
File metadata and controls
48 lines (44 loc) · 1.37 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
37
38
39
40
41
42
43
44
45
46
47
48
class Solution(object):
def combinationSum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
res = []
candidates.sort()
def dfs(t, i, path, res):
if t < 0:
return
if t == 0:
res.append(path)
return
for j in range(i, len(candidates)):
if j > i and candidates[j] == candidates[j-1]:
continue
dfs(t-candidates[j], j+1, path+[candidates[j]], res)
dfs(target, 0, [], res)
return res
# this solution don't pass, get [[],[]]. weird!
class Solution(object):
def combinationSum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
res = []
candidates.sort()
def dfs(t, cur, path):
if t == 0:
res.append(path)
return
for j in range(cur, len(candidates)):
if candidates[j] > t: break
if j > cur and candidates[j] == candidates[j-1]:
continue
path.append(candidates[j])
dfs(t-candidates[j], j+1, path)
path.pop()
dfs(target, 0, [])
return res