1 Star 0 Fork 0

catyMap/AlgorithmNote

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
combinationSum2.go 810 Bytes
一键复制 编辑 原始数据 按行查看 历史
dogemap 提交于 2021-04-25 08:32 +08:00 . 4/25新题
package main
import "sort"
// 像这种需要记录明确组合集合的,没什么好剪枝或dp的,因为剪枝和dp都会丢失一部分的信息,而这种题目要求构建树的信息是全量的
func combinationSum2(candidates []int, target int) (res [][]int) {
sort.Ints(candidates)
trace := make([]int,0,0)
var depth func(a , sum, floor int)
depth = func(idx, sum, floor int) {
if sum > target {
return
}
if sum == target {
res = append(res, append([]int{}, trace...))
}
for i := idx ; i < len(candidates) ; i ++ {
if i > idx && candidates[i-1] == candidates[i] {
continue
}
trace = append(trace, candidates[i])
sum += candidates[i]
depth(i+1 , sum, floor + 1)
trace = trace[:len(trace)-1]
sum -= candidates[i]
}
}
depth(0, 0, 0)
return res
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/dogemap/algorithm-note.git
git@gitee.com:dogemap/algorithm-note.git
dogemap
algorithm-note
AlgorithmNote
dc486f96f6c1

搜索帮助