持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第1天,点击查看活动详情
题目描述
给你一个 无重复元素 的整数数组 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 。 仅有这两种组合。
回溯
这个题目我的初步思路是:刚开始看到这道题目我就想到那道走楼梯经典算法题,不过那个是求有多少种走法,这个是把各种组合的具体内容求出来 我的思路是遍历元素,求目标值与该元素的差值,看看数组中能不能元素的和等于这个差值,但反正就是递归。这题是根据重复选择当前index元素,直到target-sum < candidates[index]才开始选择下一个元素,但是由于排序后的数组递增,下一个元素要么刚好等于target-sum,要么大于target-sum直接return,这样做可以减少回溯次数。具体实现:
- 首先先对数组进行排序,方便后面的处理。
- 然后开始遍历数组,从第0位开始取数,不断叠加直到(c[i]/target的除数)
- 如果其值 == target,则保存下来加入队列
- 如若 > target,则递减当前数的个数,循环步骤2
- 如若 < target,则取下一位
- 注意过程中我们需要把重复的结果剔除掉,使用i < nums.length && nums[i] <= t来进行剪枝,可以大大的提高效率。
class Solution {
List<List<Integer>> result = new LinkedList<>();
List<Integer> temp = new LinkedList<>();
int sum = 0;
public List<List<Integer>> combinationSum(int[] candidates, int target) {
backtrace(candidates,target,0);
return result;
}
public void backtrace(int[] candidates,int target,int index){
if (sum > target || index == candidates.length) return;
if (sum == target){
result.add(new ArrayList<>(temp));
return;
}
temp.add(candidates[index]);
sum += candidates[index];
backtrace(candidates,target,index);
sum -= temp.get(temp.size()-1);
temp.remove(temp.size()-1);
backtrace(candidates,target,index+1);
}
}
最后
注意点:本题其实很明显是一个回溯题,但其实难点在于如何保存整个
path数组:我的思路是声明一个全局变量path,用来存储当前路径,在递归调用完事之后再pop,可以保证path数组不会乱。