原题
https://leetcode.cn/problems/combination-sum/description/
思路
回溯法
复杂度
时间:O(n * n)
空间:O(n)
Python代码
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
ans = []
def dfs(start, curSum, path):
if curSum == target:
ans.append(path[:])
return
if curSum > target:
return
for i in range(start, len(candidates)):
curSum += candidates[i]
path.append(candidates[i])
dfs(i, curSum, path)
# 还原
path.pop()
curSum -= candidates[i]
dfs(0, 0, [])
return ans
Go代码
func combinationSum(candidates []int, target int) [][]int {
var ans [][]int
// 匿名函数
var dfs func(int, int, []int)
dfs = func(start int, curSum int, path []int) {
if curSum == target {
// 创建切片
com := make([]int, len(path))
// 复制切片
copy(com, path)
ans = append(ans, com)
return
}
if curSum > target {
return
}
for i := start; i < len(candidates); i++ {
curSum += candidates[i]
path = append(path, candidates[i])
dfs(i, curSum, path)
// 还原
path = path[:len(path)-1]
curSum -= candidates[i]
}
}
dfs(0, 0, []int{})
return ans
}
314

被折叠的 条评论
为什么被折叠?



