文章目录
回溯算法介绍
参考:代码随想录
1. 定义
回溯算法是一种搜索算法,回溯是递归的副产品,只要有递归就有回溯,回溯函数就是递归函数,对于回溯的优化就是剪枝
回溯是在集合中递归搜索,回溯问题可以抽象为树形结构,集合的大小构成了树的宽度(for循环),递归的深度构成了数的深度
2. 可解决的问题
- 组合问题:n个数中按一定规则找出k个数的集合
- 排列问题:n个数中按一定规则全排列
- 切割问题:一个字符串按一定规则切割
- 子集问题:n个数的集合中符合条件的子集
- 棋盘问题:n皇后,数独
3. 回溯的模板
void backreacking(参数) {
if (终止条件) {
存放结果;
return;
}
//单层遍历逻辑
for (选择:本层集合元素(树中节点孩子的数量就是结合的大小)) {
处理节点;
backreacking(路径,选择列表);//递归函数
回溯,撤销处理结果;
}
}
组合
组合无序,排列有序
77. 组合
题目:给定两个整数 n 和 k,返回范围 [1, n] 中所有可能的 k 个数的组合。你可以按 任何顺序 返回答案
链接:https://leetcode.cn/problems/combinations/
代码:
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> combine(int n, int k) {
backtracking(n, k, 1);
return res;
}
public void backtracking(int n, int k, int startIndex) {
// 终止条件
if (path.size() == k) {
res.add(new ArrayList<>(path));
return;
}
// 剪枝优化:i <= n - (k - path.size()) + 1;
for (int i = startIndex; i <= n - (k - path.size()) + 1; i ++) {
path.add(i); // 处理节点
backtracking(n, k, i + 1); // 递归
path.remove(path.size() - 1); // 回溯
}
}
216. 组合总和 III
题目:找出所有相加之和为 n 的 k 个数的组合,且满足下列条件:只使用数字1到9;每个数字 最多使用一次
返回 所有可能的有效组合的列表 。该列表不能包含相同的组合两次,组合可以以任何顺序返回。
链接:https://leetcode.cn/problems/combination-sum-iii/
代码:
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> combinationSum3(int k, int n) {
backtracking(k, n, 0, 1);
return res;
}
public void backtracking(int k, int n, int sum, int startIndex) {
// 剪枝优化
if (sum > n) return;
// 终止条件
if (path.size() == k) {
if (sum == n) {
res.add(new ArrayList(path));
return;
}
}
// 2种剪枝,卡哥是第一种,我发现第二种效果更好
// i <= 9 - (k - path.size()) + 1
// i <= 9 && sum + i <= n
for (int i = startIndex; i <= 9 && sum + i <= n; i ++) {
sum += i;
path.add(i);
backtracking(k, n, sum, i + 1);
sum -= i;
path.remove(path.size() - 1);
}
}
17. 电话号码的字母组合
题目:给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
链接:https://leetcode.cn/problems/letter-combinations-of-a-phone-number/
代码:
class Solution {
List<String> res = new ArrayList<>();
StringBuilder path = new StringBuilder();
String[] letterMap = {
"", // 0
"", // 1
"abc", // 2
"def", // 3
"ghi", // 4
"jkl", // 5
"mno", // 6
"pqrs", // 7
"tuv", // 8
"wxyz", // 9
};
public List<String> letterCombinations(String digits) {
if (digits.length() == 0) return res;
backtracking(digits, 0);
return res;
}
// index:遍历到第几个数字
public void backtracking(String digits, int index) {
// 终止条件
if (index == digits.length()) {
res.add(path.toString());
return;
}
int digit = digits.charAt(index) - '0'; // 获取数字
String letters = letterMap[digit]; // 获取字母
// 遍历
for (int i = 0; i < letters.length(); i ++) {
path.append(letters.charAt(i));
backtracking(digits, index + 1);
path.deleteCharAt(path.length() - 1);
}
}
}
39. 组合总和
题目:给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。
candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。 对于给定的输入,保证和为 target 的不同组合数少于 150 个。
链接:https://leetcode.cn/problems/combination-sum/
代码:
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates); // 后面剪枝优化需要先排序
backtracking(candidates, target, 0, 0);
return res;
}
public void backtracking(int[] candidates, int target, int sum, int startIndex) {
// 剪枝
if (sum > target) return;
// 终止条件
if (target == sum) {
res.add(new ArrayList<>(path));
return;
}
// 遍历
// 剪枝:candidates[i] + sum <= target
for (int i = startIndex; i < candidates.length && candidates[i] + sum <= target; i ++) {
sum += candidates[i];
path.add(candidates[i]);
backtracking(candidates, target, sum, i); // 注意:不是i+1,因为所取的元素是可以重复的
sum -= candidates[i];
path.remove(path.size() - 1);
}
}
}
40. 组合总和 II
题目:给定一个候选人编号的集合 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用 一次 。注意:解集不能包含重复的组合
链接:https://leetcode.cn/problems/combination-sum-ii/
思路:关键是去重操作,常规剪枝
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
boolean[] used;
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates); // 排序
backtracking(candidates, target, 0, 0);
return res;
}
public void backtracking(int[] candidates, int target, int sum, int startIndex) {
// 剪枝
if (sum > target) return;
if (sum == target) {
res.add(new ArrayList<>(path));
return;
}
for (int i = startIndex; i < candidates.length && candidates[i] + sum <= target; i ++) {
// 去重:i > startIndex 剪枝;candidates[i] + sum <= target
if (i > startIndex && candidates[i] == candidates[i - 1]) {
continue;
}
sum += candidates[i];
path.add(candidates[i]);
backtracking(candidates, target, sum, i + 1);
sum -= candidates[i];
path.remove(path.size() - 1);
}
}
}
分割
131. 分割回文串
题目:给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。
链接:tps://leetcode.cn/problems/palindrome-partitioning/
思路:分割
分割问题终止条件;双指针判断回文
代码:
class Solution {
List<List<String>> res = new ArrayList<>();
List<String> path = new ArrayList<>();
public List<List<String>> partition(String s) {
backtracking(s, 0);
return res;
}
public void backtracking(String s, int startIndex) {
// 终止条件
if (startIndex >= s.length()) {
res.add(new ArrayList<>(path));
return;
}
for (int i = startIndex; i < s.length(); i ++) {
if (isPalindorm(s, startIndex, i)) { // 是回文字符串
String str = s.substring(startIndex, i + 1);
path.add(str);
} else {
continue;
}
backtracking(s, i + 1);
path.remove(path.size() - 1);
}
}
// 双指针判断是否是回文字符串
public boolean isPalindorm(String s, int start, int end) {
for (int i = start, j = end; i < j; i ++, j--) {
if (s.charAt(i) != s.charAt(j)) {
return false;
}
}
return true;
}
}
子集
78. 子集
题目:给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)
链接:https://leetcode.cn/problems/subsets/
代码:
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> subsets(int[] nums) {
backtracking(nums, 0);
return res;
}
public void backtracking(int[] nums, int startIndex) {
// 可以不加终止条件
res.add(new ArrayList<>(path));
for (int i = startIndex; i < nums.length; i ++) {
path.add(nums[i]);
backtracking(nums, i + 1);
path.remove(path.size() - 1);
}
}
}
90. 子集 II
题目:给你一个整数数组 nums ,其中可能包含重复元素,请你返回该数组所有可能的子集(幂集)。
解集 不能 包含重复的子集。返回的解集中,子集可以按 任意顺序 排列
链接:https://leetcode.cn/problems/subsets-ii/
思路:排序+去重
代码:
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> subsetsWithDup(int[] nums) {
Arrays.sort(nums);
backtracking(nums, 0);
return res;
}
public void backtracking(int[] nums, int startIndex) {
res.add(new ArrayList<>(path));
for (int i = startIndex; i < nums.length; i ++) {
// 去重
if (i > startIndex && nums[i - 1] == nums[i]) {
continue;
}
path.add(nums[i]);
backtracking(nums, i + 1);
path.remove(path.size() - 1);
}
}
}
排列
491. 递增子序列
题目:给你一个整数数组 nums ,找出并返回所有该数组中不同的递增子序列,递增子序列中 至少有两个元素 。你可以按 任意顺序 返回答案。
数组中可能含有重复元素,如出现两个整数相等,也可以视作递增序列的一种特殊情况
链接:https://leetcode.cn/problems/increasing-subsequences/
思路:注意:此题不能对原数组进行排序
题目要求递增子序列,如果排序后去重结果不正确
代码:
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> findSubsequences(int[] nums) {
backtracking(nums, 0);
return res;
}
public void backtracking(int[] nums, int startIndex) {
if (path.size() >= 2) {
res.add(new ArrayList<>(path));
}
int[] used = new int[201]; // 题目说数值范围[-100, 100]
for (int i = startIndex; i < nums.length; i ++) {
// 注意:此题不能事先对数组进行排序,题目要求需要求递增子序列,因此原来的去重方法就不能使用了
//
if (!path.isEmpty() && nums[i] < path.get(path.size() - 1) || (used[nums[i] + 100] == 1)) continue;
used[nums[i] + 100] = 1; // 记录这个元素在本层用过了,本层后面不能再用了
path.add(nums[i]);
backtracking(nums, i + 1);
path.remove(path.size() - 1);
}
}
}
46. 全排列
题目:给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案
链接:https://leetcode.cn/problems/permutations/
思路:回溯,used数组记录元素是否已被使用
代码:
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
boolean[] used;
public List<List<Integer>> permute(int[] nums) {
used = new boolean[nums.length];
backtracking(nums);
return res;
}
public void backtracking(int[] nums) {
// 说明找到了一组排列
if (path.size() == nums.length) {
res.add(new ArrayList<>(path));
return;
}
for (int i = 0; i < nums.length; i ++) {
if (used[i] == true) continue; // path里已经收录的元素
used[i] = true;
path.add(nums[i]);
backtracking(nums);
used[i] = false;
path.remove(path.size() - 1);
}
}
}
47. 全排列 II
题目:给定一个可包含重复数字的序列 nums ,按任意顺序 返回所有不重复的全排列。
链接:https://leetcode.cn/problems/permutations-ii/
思路:关键:去重
代码:
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
boolean[] used;
public List<List<Integer>> permuteUnique(int[] nums) {
used = new boolean[nums.length];
Arrays.sort(nums);
backtracking(nums);
return res;
}
public void backtracking(int[] nums) {
if (path.size() == nums.length) {
res.add(new ArrayList<>(path));
return;
}
for (int i = 0; i < nums.length; i ++) {
// 去重:i > 0 && nums[i] == nums[i - 1] && used[i - 1] == false
// used[i] == true:path中已收录该元素
if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == false || used[i] == true) continue;
used[i] = true;
path.add(nums[i]);
backtracking(nums);
used[i] = false;
path.remove(path.size() - 1);
}
}
}