分解方法:
1 当前处理第一个或最后一个,对其余的递归
2 一分为二,对两边做递归
3 在一系列选择中做一个选择,对更新的状态做递归
回溯问题:
1 Design recursion function to return success/failure
2 At each call, choose one option and go with it
3 Recursively proceed and see what happens
4 If it works out, great! Otherwise, unmake choice and try again
5 If no option worked, return fail result which triggers backtracking (i.e. un-marking earlier decision)
注意:如果题目要求只求出是否可行,而并不要求求出所有的解,这时要有返回值,为了尽快的结束
但如果题目要求求出所有的解,这时就没必要返回值,可以是void。
举例:
1 如果求一个数独是否可解,这时就要有返回值,因为只要找到一个就可以停止了
2 如果要求找到所有数独的解,这时就没必要用boolean返回了。
但是无论哪一种情况,做选择与撤销选择,这个步骤是一定要做的!
Heuristics may help efficiency:
1 Eliminate dead ends early by pruning
2 Pursue most likely choices first.
熟练写出subset和permutation,8皇后模型!
还可以参考总结好的 :总结帖:全排列Permutation,子集subset 递归模板
Backtrack pseudocode:
bool solve(configuration conf){
if(no more choices){ // BASE CASE
return (conf is goal state);
}
for(all available choices){
try one choice c:
// Solve from here, if works out, you're done!
if(solve(conf with choice c made)) return true; // Stop early!
unmake choice c;
}
return false; // tried all choices, no solution found
}
具体例子可参考: