原题
https://leetcode.cn/problems/combination-sum-ii/description/
思路
回溯法, 需要去重
复杂度
时间:O(n * n)
空间:O(n)
Python代码
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
candidates.sort()
length = len(candidates)
ans = []
def dfs(start, curSum, path):
if curSum == target:
ans.append(path[:])
return
if curSum > target:
return
for i in range(start, length):
if i > start and candidates[i] == candidates[i-1]:
continue
curSum += candidates[i]
path.append(candidates[i])
dfs(i+1, curSum, path)
# 还原
curSum -= candidates[i]
path.pop()
dfs(0, 0, [])
return ans
Go代码
func combinationSum2(candidates []int, target int) [][]int {
sort.Ints(candidates)
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)
}
if curSum > target {
return
}
for i := start; i < len(candidates); i++ {
// 去重
if i > start && candidates[i] == candidates[i-1] {
continue
}
curSum += candidates[i]
path = append(path, candidates[i])
dfs(i+1, curSum, path)
// 还原
curSum -= candidates[i]
path = path[:len(path)-1]
}
}
dfs(0, 0, []int{})
return ans
}

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



