给定一个包含一些数字的列表和一个目标值,在这个列表中所有结果的和是目标值的组合
思路: dfs
Python:
class Solution:
def combinationSum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
# 5 star, dfs,需要注意去重
candidates.sort()
rs = []
self.dfs(0, candidates, [], rs, target)
return rs
def dfs(self, current_sum, candidates, path, rs, target):
if current_sum == target:
rs.append(path)
return
elif current_sum > target:
return
else:
for i in range(len(candidates)):
if i > 0 and candidates[i] == candidates[i-1]:
continue
if current_sum + candidates[i] > target:
break
self.dfs(current_sum+candidates[i], candidates[i+1:], path+[candidates[i]], rs, target)
Go:
func combinationSum2(candidates []int, target int) [][]int {
var ret [][]int
retP := &ret
sort.Ints(candidates)
dfs(candidates, target, 0, []int{}, retP)
return *retP
}
func dfs(candidates []int, target int, curSum int, path []int, retP *[][]int) {
if curSum == target {
tempPath := make([]int, len(path)) //创建了切片的拷贝,避免后续的修改影响已加入结果集的切片的取值
copy(tempPath, path)
*retP = append(*retP, tempPath)
return
}
for index, val := range candidates {
if index == 0 || candidates[index] > candidates[index-1] { //避免重复
if curSum + val > target {
return
} else {
dfs(candidates[index+1:], target, curSum+val, append(path, val), retP)
}
}
}
}