essay
hot100-组合总和
#算法
hot100——组合总和
给你一个 无重复元素 的整数数组 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
2 <= candidates[i] <= 40
candidates 的所有元素 互不相同
1 <= target <= 40
解法
import "sort"
// combinationSum 返回所有和为 target 的组合,每个数字可重复使用
func combinationSum(candidates []int, target int) [][]int {
// 先排序,方便剪枝
sort.Ints(candidates)
res := make([][]int, 0)
path := make([]int, 0)
backtrack(candidates, target, 0, 0, path, &res)
return res
}
// backtrack 递归回溯函数
// candidates: 候选数组(已排序)
// target: 目标和
// start: 当前可选数字的起始下标(允许重复选取,所以下一轮从 i 开始)
// sum: 当前路径的和
// path: 当前已选择的数字序列
// res: 指向结果集的指针
func backtrack(candidates []int, target int, start int, sum int, path []int, res *[][]int) {
// 如果当前和等于目标,找到一个有效组合
if sum == target {
// 复制一份 path,避免后续修改影响结果
tmp := make([]int, len(path))
copy(tmp, path)
*res = append(*res, tmp)
return
}
// 剪枝:由于数组已排序,如果当前和加上 candidates[i] 已经大于 target,
// 则后续更大元素也一定大于 target,可以提前结束循环
for i := start; i < len(candidates) && sum+candidates[i] <= target; i++ {
// 做选择:将 candidates[i] 加入路径
path = append(path, candidates[i])
// 递归:注意下一轮起始下标仍是 i(允许重复使用同一元素)
backtrack(candidates, target, i, sum+candidates[i], path, res)
// 撤销选择:回溯
path = path[:len(path)-1]
}
}