一、理论
回溯
- 本质:和深度优先遍历思想是一致的,都是递归的应用;搜索空间可以理解成一棵树,需要自顶向下不断枚举出所有的情况。
- 写法的关键:循环和递归。
- for循环的作用在于另寻它路,可以逐个选择当前节点下的所有可能往下走下去的分支路径。
- 递归可以实现一条路走到黑和回退一步,把递归放在for循环内部,那么for每一次的循环,都在给出一个路径后进入递归,继续往下走。
- 代码模版
void backtracking(参数) {
if (终止条件) {
存放结果;
return;
}
for (选择:本层集合中元素(树中节点孩子的数量就是集合的大小)) {
处理节点;
backtracking(路径,选择列表); // 递归
回溯,撤销处理结果
}
}
剪枝
- 定义:剪枝算法是排除搜索空间中不可能包含最优解的部分,从而减少搜索时间以及空间复杂度。
- 实现方式:
A. 可行性剪枝
利用问题的特性进行剪枝;在搜索过程中,根据问题的特点,排除不符合条件的搜索分支。
B. 排除等效冗余
当几个枝桠具有完全相同的效果的时候,只选择其中一个走就可以了。
C. 最优性剪枝
所谓最优性剪枝,是在我们用搜索方法解决最优化问题的时候的一种常用剪枝方法。当搜到一半的时候,发现比已经搜索到的最优解差,则该方案肯定是不行的,即刻停止搜索,进行回溯。
D. 顺序剪枝
普遍来讲,搜索的顺序是不固定的,对一个问题来讲,算法可以进入搜索树的任意的一个子节点。但假如我们要搜索一个最小值,而非要从最大值存在的那个节点开搜,就可能存在搜索到最后才出解。而我们从最小的节点开搜很可能马上就出解。这就是顺序剪枝的一个应用。一般来讲,有单调性存在的搜索问题可以和贪心思想结合,进行顺序剪枝。
E. 记忆化搜索
记忆化搜索其实是搜索的另外一个分支。在这里简单介绍一下记忆化的原理:就是记录搜索的每一个状态,当重复搜索到相同的状态的时候直接返回。
二、算法实践
问题链接
37. 解数独
问题描述
编写一个程序,通过填充空格来解决数独问题。
数独的解法需 遵循如下规则:
数字 1-9
在每一行只能出现一次。
数字 1-9
在每一列只能出现一次。
数字 1-9
在每一个以粗实线分隔的 3x3
宫内只能出现一次。(请参考示例图)
数独部分空格内已填入了数字,空白格用 '.' 表示。
示例
输入:board = [["5","3",".",".","7",".",".",".","."],["6",".",".","1","9","5",".",".","."],[".","9","8",".",".",".",".","6","."],["8",".",".",".","6",".",".",".","3"],["4",".",".","8",".","3",".",".","1"],["7",".",".",".","2",".",".",".","6"],[".","6",".",".",".",".","2","8","."],[".",".",".","4","1","9",".",".","5"],[".",".",".",".","8",".",".","7","9"]]
输出:[["5","3","4","6","7","8","9","1","2"],["6","7","2","1","9","5","3","4","8"],["1","9","8","3","4","2","5","6","7"],["8","5","9","7","6","1","4","2","3"],["4","2","6","8","5","3","7","9","1"],["7","1","3","9","2","4","8","5","6"],["9","6","1","5","3","7","2","8","4"],["2","8","7","4","1","9","6","3","5"],["3","4","5","2","8","6","1","7","9"]]
解题思路
- 遍历整个数独,获取数字在行、列、宫格中的出现情况,以及空闲位置。
- 用递归的方法,给空闲位置挨个放数,放数的同时校验行、列、宫格内的重复性,如果发生重复,就剪掉并回溯。
代码示例(JAVA)
class Solution {
// 表示行、列、宫格中数字的出现情况
private boolean[][] row = new boolean[9][9];
private boolean[][] column = new boolean[9][9];
private boolean[][][] grid = new boolean[3][3][9];
// 找出需要放入数字的位置
private List<int[]> empty = new ArrayList<int[]>();
public void solveSudoku(char[][] board) {
// 遍历整个数独,获取数字在行、列、宫格中的出现情况,以及空闲位置
for (int i = 0; i < 9; ++i) {
for (int j = 0; j < 9; ++j) {
if (board[i][j] == '.') {
empty.add(new int[]{i, j});
} else {
int index = board[i][j] - '0' - 1;
row[i][index] = column[j][index] = grid[i / 3][j / 3][index] = true;
}
}
}
dfs(board, 0);
}
public boolean dfs(char[][] board, int pos) {
// 递归终止条件
if (pos == empty.size()) {
return true;
}
int[] target = empty.get(pos);
int i = target[0], j = target[1];
for (int k = 0; k < 9; ++k) {
// 经过校验,可以放入k;校验失败就不要了(剪枝)
if (!row[i][k] && !column[j][k] && !grid[i /3][j / 3][k]) {
// 放入k,并更新数字出现情况,且继续递归
board[i][j] = (char) (k + '0' + 1);
row[i][k] = column[j][k] = grid[i / 3][j / 3][k] = true;
// 递归到下一层
if (dfs(board, pos + 1)) {
return true;
}
// 失败,回溯
row[i][k] = column[j][k] = grid[i / 3][j / 3][k] = false;
}
}
// 找不到可以放入的k,return false
return false;
}
}