题目
给定一个候选人编号的集合 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用 一次 。
注意:解集不能包含重复的组合。
示例
输入: candidates = [10,1,2,7,6,1,5], target = 8,
输出:[[1,1,6],[1,2,5],[1,7],[2,6]]
解析
本题中每个数字在每个组合中可以使用多次;但最后的组合不能有相同的;
本题中原始数据中有重复元素;
也就是说,树的深度不用去重,宽度的时候需要去重;
而上一道题,是原始数据中没有重复元素,但一个元素可以用多次;
注意:这种的剪枝都需要排序
func combinationSum2(candidates []int, target int) [][]int {
var path []int
var res [][]int
sort.Ints(candidates) //也是需要排序
backtracking(0, 0, target, candidates, path, &res)
return res
}
func backtracking(startIndex, sum, target int, candidates, path []int, res *[][]int) {
if sum == target {
tmp := make([]int, len(path))
copy(tmp, path)
*res = append(*res, tmp)
return
}
if sum > target {
return
}
for i := startIndex; i < len(candidates) && sum + candidates[i] <= target; i++ {
// 如果当前树层有使用过相同元素,则continue
if i > startIndex && candidates[i] == candidates[i-1] {
continue // 注意是continue,不是return
}
path = append(path, candidates[i])
sum += candidates[i]
backtracking(i+1, sum, target, candidates, path, res) //这里是i+1,因为每个数字在每个组合中只能用一次
path = path[:len(path)-1]
sum -= candidates[i]
}
}
为什么说上面的判断条件中,树层去重可以用:
if i > startIndex && candidates[i] == candidates[i-1] {
continue // 注意是continue,不是return
}
来判断呢?startIndex是用来判断每一层的起始标志位的,想不明白的话也可以用一个used数组来记录
func combinationSum2(candidates []int, target int) [][]int {
var path []int
var res [][]int
used := make([]bool, len(candidates))
sort.Ints(candidates) //也是需要排序
backtracking(0, 0, target, candidates, path, &res, used)
return res
}
func backtracking(startIndex, sum, target int, candidates, path []int, res *[][]int, used []bool) {
if sum == target {
tmp := make([]int, len(path))
copy(tmp, path)
*res = append(*res, tmp)
return
}
if sum > target {
return
}
for i := startIndex; i < len(candidates) && sum+candidates[i] <= target; i++ {
// 如果当前树层有使用过相同元素,则continue
// used[i - 1] == true,说明同一树枝candidates[i - 1]使用过
// used[i - 1] == false,说明同一树层candidates[i - 1]使用过
if i > 0 && candidates[i] == candidates[i-1] && !used[i-1] {
continue // 注意是continue,不是return
}
path = append(path, candidates[i])
sum += candidates[i]
used[i] = true
backtracking(i+1, sum, target, candidates, path, res, used) //这里是i+1,因为每个数字在每个组合中只能用一次
path = path[:len(path)-1]
sum -= candidates[i]
used[i] = false
}
}