https://leetcode.cn/problems/combination-sum/
题目要求
给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。
candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。
对于给定的输入,保证和为 target 的不同组合数少于 150 个。
回溯
class Solution {
List<List<Integer>> res = new ArrayList<>();
LinkedList<Integer> list = new LinkedList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
backtrack(0, candidates, target);
return res;
}
public void backtrack(int index, int[] candidates, int target) {
// 递归终止条件
if (target == 0) {
res.add(new ArrayList<>(list));
return;
}
// 循环回溯
for (int i = index; i < candidates.length; i++) {
if (target < candidates[i])
break;
list.add(candidates[i]);
backtrack(i, candidates, target - candidates[i]);
list.removeLast();
}
}
}
- 下一层的递归不使用i+1,就可以重复选取当前元素;
- 排序是为了进行剪枝,不进行后面的递归直接结束;