「这是我参与2022首次更文挑战的第38天,活动详情查看:2022首次更文挑战」
39. 组合总和
给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。
candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。
示例 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
搜索回溯
思路 这道题目是在给定数组candidates中选择数组来组成目标target的值,candidates中的元素可以重复选取,求所有的结果
这里我们使用搜索回溯的方法来做
我们可以通过深度优先遍历的方式去处理每一种情况
用dfs函数来递归实现
我们需要分别去处理数组中遇到的没一个数字,每个数字都有两种情况,选择和不选择,并且可以重复选择
因此我们用index表示,candidates中的第index个数字
- 不选择,则直接跳到index+1,其它不变
- 选择,则需要满足target>candidates[index]的条件,target要减去当前数字,因为选择了所以index不变,调用过的数字栈stack需要克隆并加入当前元素
当candidates中的元素遍历完毕则结束
当target的值为0的时候满足条件,将stack放入结果数组ans中
var combinationSum = function (candidates, target) {
// 思路
// 回溯
// dfs 深度优先遍历
// 0. 参数介绍 index,当前使用candidates中的第几个数字,stack当前使用的数字栈[],target,target当前要找的目标
// 1. 判断target是否为0,为0则直接返回
// 2. 数组循环完毕则
// 3. 当前index值不要直接跳到index+1
// 4. 当前index的值要,但是需要满足条件 target>=curr
var ans = []
var len = candidates.length
var dfs = function (index, stack, target) {
// 1
if (index === len) {
return
}
// 2
if (target === 0) {
ans.push(stack)
return
}
// 3
dfs(index + 1, stack, target)
// 4
if (target >= candidates[index]) {
dfs(index, [...stack,candidates[index]], target - candidates[index])
}
}
// 执行dfs
dfs(0,[],target)
return ans
};
谢谢大家,一起加油