一、回溯算法基础
回溯法也叫回溯搜索法,它是一种搜索的方式。回溯是递归的副产品,只要有递归就会有回溯。
回溯法的效率——虽然回溯法很难,很不好理解,但是回溯法并不是什么高效的算法。因为回溯的本质是穷举,穷举所有可能,然后选出我们想要的答案,剪枝的操作可以让回溯法高效一点,但是仍然不能改变回溯法的本质
回溯法解决的问题——
- 组合问题:N个数里按一定规则找出k个数的集合
- 切割问题:一个字符串按一定规则有几种切割方式
- 子集问题:一个N个数的集合里有多少符合条件的子集
- 排列问题:N个数按照一定规则全排列,有几种排列方式
- 棋盘问题:N皇后,解数独等等
组合无序,排列有序。
如何理解回溯法——
伪代码
void backtracking(参数)
回溯函数的终止条件
if (终止条件) {
存放结果;
return;
}
回溯搜索的遍历过程
for (选择:本层集合中元素(树中节点孩子的数量就是集合的大小)){
处理节点;
backtracking(路径,选择列表); //递归
回溯,撤销处理结果
}
for循环可以理解是横向遍历,backtracking(递归)就是纵向遍历
回溯法抽象为树形结构后,其遍历过程就是:for循环横向遍历,递归纵向遍历,回溯不断调整结果集。
二、刷题
1. 77. 组合【中等】
//未剪枝优化
class Solution {
List<List<Integer>> result = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> combine(int n , int k) {
backtracking(n,k,1);
return result;
}
public void backtracking(int n , int k, int startIndex){
if(path.size() == k){
result.add(new ArrayList<>(path));
return;
}
for(int i = startIndex; i <= n;i++){
path.add(i);
backtracking(n,k,i+1);
path.removeLast();
}
}
}
剪枝优化过程
1. 已经选择的元素个数:path.size()
2. 还需要选择的元素个数为:k - path.size()
3. 在集合n中至多要从该其实位置:n - (k-path.size()) + 1,开始遍历
为什么会有+1? 因为包括开始的位置,需要一个左闭的集合。
//剪枝
class Solution {
List<List<Integer>> result = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> combine(int n, int k) {
backtracking(n,k,1);
return result;
}
/**
每次从集合中选取元素,可选择的范围随着选择的进行而收缩,调整可选择的范围,就是要靠startIndex
@param startIndex 用来记录本层递归的中,集合从哪里开始遍历(集合就是[1,...,n] )。
*/
private void backtracking(int n , int k, int startIndex){
//终止条件
if(path.size() == k){
result.add(new ArrayList<>(path));
return;
}
for(int i = startIndex;i <= n - (k-path.size())+1;i++){
path.add(i);
backtracking(n,k,i+1);
path.removeLast();
}
}
}
2. 216. 组合总和 III
class Solution {
List<List<Integer>> result = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> combinationSum3(int k, int n) {
combineHelper(n,k,1,0);
return result;
}
public void combineHelper(int target,int k,int startIndex,int sum){
//剪枝
if(sum > target){
return ;
}
//终止条件
if(path.size() == k){
if(sum == target){
result.add(new ArrayList(path));
}
return;
}
//剪枝 9- (k- path.size())+1
for(int i = startIndex;i <= 9- (k- path.size())+1;i++ ){
path.add(i);
sum += i;
combineHelper(target,k,i+1,sum);
//回溯,剔除掉不合适的,继续移动
path.removeLast();
//回溯
sum -= i;
}
}
}
3. 17. 电话号码的字母组合【中等】
主要解决三个问题
- 数字和字母如何映射
- 两个字母就两个for循环,以此类推写不出来
- 输入1*#按键等等异常情况
回溯三部曲:
- 确定回溯的参数:字符串s收集叶子节点的结果,字符串数组result收集结果,string digits,int index用来遍历digits,也表示树的深度
- 确定终止条件:终止条件就是如果index 等于 输入的数字个数(digits.size)了(本来index就是用来遍历digits的
- 确定单层遍历逻辑:本题每一个数字代表的是不同集合,也就是求不同集合之间的组合。for循环遍历会不一样
class Solution {
List<String> result = new ArrayList<>();
String s;
public List<String> letterCombinations(String digits) {
//剪枝
if(digits == null || digits.length() == 0){
return result;
}
//初始对应所有的数字,为了直接对应2-9,新增两个无效的字符串“”
String[] numString = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
//迭代处理
backTracking(digits,numString,0);
return result;
}
//每次迭代获取一个字符串,所以会设计大量的字符串拼接,所以这里选择更为高效的 StringBuild
StringBuilder temp = new StringBuilder();
//比如digits如果为"23",num 为0,则str表示2对应的 abc
public void backTracking(String digits,String[] numString,int num){
//遍历全部一次记录一次得到的字符串
if (num == digits.length()){
result.add(temp.toString());
return;
}
//str表示当前num对应的字符串
String str = numString[digits.charAt(num)-'0'];
for(int i =0;i < str.length();i++){
temp.append(str.charAt(i));
//回溯
backTracking(digits,numString,num+1);
//剔除末尾的继续尝试
temp.deleteCharAt(temp.length()-1);
}
}
}