持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第7天,点击查看活动详情
组合总和
给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。
candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。
对于给定的输入,保证和为 target 的不同组合数少于 150 个。
示例 1:
输入:candidates = [2,3,6,7], target = 7
输出:[[2,2,3],[7]]
解释:
2 和 3 可以形成一组候选,2 + 2 + 3 = 7 。注意 2 可以使用多次。
7 也是一个候选, 7 = 7 。
仅有这两种组合。
示例 2:
输入: candidates = [2,3,5], target = 8
输出: [[2,2,2,2],[2,3,3],[3,5]]
示例 3:
输入: candidates = [2], target = 1
输出: []
提示:
- 1 <= candidates.length <= 30
- 1 <= candidates[i] <= 200
- candidate 中的每个元素都 互不相同
- 1 <= target <= 500
解题思路
暴力递归
总结:
-
递归的思路要再学习,尤其是结果的存放,这里是用一个全局变量来存储的。
-
递归的过程中是没有 return 的,否则找到结果就 return 就无法遍历到所有情况
-
递归就像是深度遍历,左分支走完后需要重置恢复现场再进行右分支遍历 特别注意:
-
Go 中切片“引用”传递的特性
-
全局变量最好在函数入口处重置一下,否则在提交后前一次的执行结果会污染到后面的结果
-
用闭包的方式可以避免全局变量污染的问题
-
二合一用法: result = append(result, append([]int(nil), chosen...))
代码实现
var result [][]int
func combinationSum(candidates []int, target int) [][]int {
result = make([][]int, 0, 100) // 每次开始重置全局变量,以防上次的结果影响
candidates = formatCandidates(candidates, target)
if len(candidates) == 0 {
return nil
}
digui(candidates, []int{}, target)
return result
}
func digui(candidates, chosen []int, target int) {
if target == 0 {
temp := append([]int{}, chosen...) // 需要重新分配
result = append(result, temp)
return
}
if len(candidates) == 0 || target < 0 {
return
}
// 计
chosen = append(chosen, candidates[0])
digui(candidates[:], chosen, target-candidates[0])
// 无
chosen = chosen[:len(chosen)-1]
digui(candidates[1:], chosen, target)
}
func formatCandidates(candidates []int, target int) []int {
sort.Ints(candidates)
i := len(candidates) - 1
for ; i >= 0 && candidates[i] > target; i-- {
}
return candidates[0 : i+1]
}