class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
// 储存所有满足条件的组合
List<List<Integer>> result = new ArrayList<>();
// 储存当前组合
List<Integer> combination = new ArrayList<>();
backtrack(candidates, target, result, combination, 0);
return result;
}
// 回溯法
private void backtrack(int[] candidates, int target, List<List<Integer>> result, List<Integer> combination, int start){
// 如果目标值为 0, 说明当前组合满足条件 将其添加到结果列表中
if(target == 0){
result.add(new ArrayList<>(combination));
return;
}
//遍历候选数组, 从start 索引开始
for(int i = start; i< candidates.length; i++){
int num = candidates[i];
// 如果当前数字小于等于目标值, 则可以将其加入到当前组合
if(num <= target){
combination.add(num);
//继续回溯,此时目标值减去当前数字,下一轮搜索仍从当前索引开始,因为可以重复使用当前数字
backtrack(candidates, target - num, result, combination, i);
//回溯完成后,移除最后一个元素,尝试其他数字
combination.remove(combination.size() - 1);
}
}
}
}
代码随想录算法训练营第27天第七章 回溯算法part03● 39. 组合总和● 40.组合总和II● 131.分割回文串
最新推荐文章于 2024-06-12 10:00:23 发布