7.6 leetcode

今日leetcode主要学习了DFS即深度优先搜索这一算法,效果还可以,但感觉复杂度还蛮高的,用到别的问题会出现TLE问题。

  1. P39

P39

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
class :	
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
res = []
candidates.sort()
self.dfs(candidates, target, 0, [], res)
return res

def dfs(self, nums, target, index, path, res):
if target < 0:
return
elif target == 0:
res.append(path)
return

for i in range(index, len(nums)):
self.dfs(nums, target-nums[i], i, path + [nums[i]], res)

sol = Solution()
out = sol.combinationSum([2, 3, 6, 7], 7)
print(out)

  1. P40
    P40

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
class :
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
res = []
candidates.sort()
self.dfs(candidates, target, 0, [], res)
real_out = {}
for o in res:
a = tuple(o)
real_out.setdefault(a)

rr_out = []
for r in real_out.keys():
r = list(r)
rr_out.append(r)

return rr_out

def dfs(self, nums, target, index, path, res):
if target < 0:
return
elif target == 0:
res.append(path)
return

for i in range(index, len(nums)):
self.dfs(nums, target-nums[i], i+1, path + [nums[i]], res)

sol = Solution()
out = sol.combinationSum([1, 0, -1, 0, -2, 2], 0)
print(out)