回溯法三部曲
- 递归函数的返回值以及参数
- 回溯函数终止条件
-
单层搜索的过程
回溯模板
void backtracking(参数) {
if (终止条件) {
存放结果;
return;
}
for (选择:本层集合中元素(树中节点孩子的数量就是集合的大小)) {
处理节点;
backtracking(路径,选择列表); // 递归
回溯,撤销处理结果
}
}
递归三部曲
- 确定递归函数的参数和返回值
- 确定终止条件
- 确定单层递归的逻辑
递归模板
void recursion(int level, int param) {
// recursion terminator
if (level > MAX_LEVEL) { // 一、递归终结条件
// process result
return ;
}
// process current logic
process(level, param); // 二、处理当前层逻辑
// drill down
recursion(level + 1, param);// 三、下探到下一层
}