39.组合总和
1.题目

2.我的解决方案
- 自己写的回溯算法,虽然进行了剪枝,但是从运行时间上来看,效果还是不行
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
def dfs(candidates, target, begin, path, res):
if path:
if sum(path) == target:
res.append(path[:])
if sum(path) > target:
return
for i in range(candidates.index(begin), len(candidates)):
path.append(candidates[i])
dfs(candidates, target, candidates[i], path, res)
path.pop()
res = []
path = []
candidates.sort()
dfs(candidates, target, candidates[0], path, res)
return res
- 时间复杂度:O(n!)O(n!)O(n!)
- 空间复杂度:O(target)O(target)O(target) 最差情况下递归target层
3.官方的解决方案
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
def dfs(begin, path, remain):
for i in range(begin, len(candidates)):
num = candidates[i]
if num == remain:
path.append(num)
res.append(path[:])
path.pop()
return
if num < remain:
path.append(num)
dfs(i, path, remain-num)
path.pop()
if num > remain:
return
res = []
path = []
candidates.sort()
dfs(0, path, target)
return res
- 时间复杂度:O(n!)O(n!)O(n!)
- 空间复杂度:O(target)O(target)O(target) 最差情况下递归target层