代码随想录 算法训练 Day23:回溯算法part02
题目一
给你一个 无重复元素 的整数数组 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
输出: []
class Solution {public List<List<Integer>> combinationSum(int[] candidates, int target) {// 结果列表List<List<Integer>> result = new ArrayList<>();// 对硬币面值排序(重要!为剪枝做准备)Arrays.sort(candidates);// 开始回溯搜索backtrack(candidates, target, 0, new ArrayList<>(), 0, result);return result;}private void backtrack(int[] candidates, int target, int start, List<Integer> current, int currentSum,List<List<Integer>> result) {// 当前组合总额等于目标 → 找到有效组合if (currentSum == target) {result.add(new ArrayList<>(current)); // 创建新列表保存当前组合return;}// 从给定位置开始尝试(保证唯一顺序)for (int i = start; i < candidates.length; i++) {int coin = candidates[i];// 检查加入是否会超出目标金额if (currentSum + coin > target) {break; // 排序后,后面硬币更大 → 直接终止}// 选择当前硬币current.add(coin); // 加入组合currentSum += coin; // 更新总额// 重要:下一个位置从i开始(允许重复使用硬币)backtrack(candidates, target, i, current, currentSum, result);// 回溯:移除最后选择的硬币current.remove(current.size() - 1);currentSum -= coin;}}
}
题目二
给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用一次。
说明: 所有数字(包括目标数)都是正整数。解集不能包含重复的组合。
- 示例 1:
- 输入: candidates = [10,1,2,7,6,1,5], target = 8,
- 所求解集为:
[[1, 7],[1, 2, 5],[2, 6],[1, 1, 6]
]
- 示例 2:
- 输入: candidates = [2,5,2,1,2], target = 5,
- 所求解集为:
[[1,2,2],[5]
]
class Solution {public List<List<Integer>> combinationSum2(int[] candidates, int target) {// 结果列表List<List<Integer>> result = new ArrayList<>();// 对硬币面值排序(重要!为剪枝做准备)Arrays.sort(candidates);backtrack(candidates, target, 0, new ArrayList<>(), 0, result);return result;}private void backtrack(int[] candidates, int target, int start, List<Integer> current, int currentSum,List<List<Integer>> result) {// 当前组合总额等于目标 → 找到有效组合if (currentSum == target) {result.add(new ArrayList<>(current)); // 创建新列表保存当前组合return;}// 从给定位置开始尝试(保证唯一顺序)for (int i = start; i < candidates.length; i++) {// 关键:跳过同一层级的重复元素if (i > start && candidates[i] == candidates[i-1]) {continue;}int coin = candidates[i];// 检查加入是否会超出目标金额if (currentSum + coin > target) {break; // 排序后,后面硬币更大 → 直接终止}// 选择当前硬币current.add(coin); // 加入组合currentSum += coin; // 更新总额// 重要:下一个位置从i开始(允许重复使用硬币)backtrack(candidates, target, i+1, current, currentSum, result);// 回溯:移除最后选择的硬币current.remove(current.size() - 1);currentSum -= coin;}}
}
题目三
先缺着