文章目录
题目描述
题解思路
按升序排序candidates,然后遍历candidates,目标数减去当前candidates的数,若该结果小于0,因为candidates的元素大于0,所以后续不会再出现让计算结果等于0的情况,所以直接break,如果该结果等于0,将数据加到结果集合中,然后break,若该结果大于0,则将当前candidates的数加入tmp数组,递归调用,调用结束后,删去tmp中添加的当前candidates的数,然后去掉和当前candidates的数重复的数
题解代码
go
func combinationSum2(candidates []int, target int) [][]int {
sort.Ints(candidates)
res := make([][]int, 0)
var dfs func([]int, int)
tmp := []int{}
dfs = func(candidates []int, target int) {
n := len(candidates)
for i := 0; i < n; i++ {
temp := target - candidates[i]
if temp < 0 {
break
}
if temp == 0 {
res = append(res, append([]int{}, append(tmp, candidates[i])...))
break
}
tmp = append(tmp, candidates[i])
dfs(candidates[i+1:], temp)
tmp = tmp[:len(tmp)-1]
for i < n - 1 && candidates[i] == candidates[i+1] {
i++
}
}
}
dfs(candidates, target)
return res
}