回溯算法
https://www.bilibili.com/video/BV1cy4y167mM/
https://leetcode-cn.com/problems/subsets/solution/78-zi-ji-hui-su-sou-suo-fa-jing-dian-ti-mu-xiang-2/
https://mp.weixin.qq.com/s/r73thpBnK1tXndFDtlsdCQ
1、概述
回溯算法并不是一种很高效率的算法,它只是一种在for循环嵌套暴力搜索时候写不出来解法的替代品,本质上是利用递归和循环的抽象思想
2、问题
回溯算法可以解决的问题?
-
组合问题:N个数里面按一定规则找出k个数的集合
-
排列问题:N个数按一定规则全排列,有几种排列方式
-
切割问题:一个字符串按一定规则有几种切割方式
-
子集问题:一个N个数的集合里有多少符合条件的子集
-
棋盘问题:N皇后,解数独等等
3、回溯深入
回溯法通常可以可以抽象为一种树形结构(n叉树)
[]
/ | \
[] [] []
/ \ / \ / \
一般来说,树的宽度就是处理的集合的大小(for循环遍历),树的深度是递归的深度(递归处理)
回溯法的一般模板:
// 伪代码
void backtracking(参数) {
if (终止条件) {
存放结果;
return;
}
for (选择:本层集合中元素(树中节点孩子的数量就是集合的大小)) {
处理节点;
backtracking(路径,选择列表); // 递归
回溯,撤销处理结果
}
}
组合问题的剪枝操作优化(21ms - > 2ms)
class Solution {
List<List<Integer>> ans = new ArrayList<>();
public List<List<Integer>> combine(int n, int k) {
backtracking(new ArrayList<Integer>(), 1, n, k);
return ans;
}
void backtracking(List<Integer> temp, int start, int end, int k){
if(temp.size() == k){
ans.add(new ArrayList<>(temp));
return;
}
// |->------------剪枝-----------<-|
for(int i = start; i <= end - (k - temp.size()) + 1; i++){
temp.add(i);
backtracking(temp, i + 1, end, k);
temp.remove(temp.size() - 1);
}
}
}