我迄今使用的所有回溯算法都是基于递归的。但我找不到任何证据表明回溯不能是非递归的。那么问题是,回溯算法是否总是使用递归?
我迄今使用的所有回溯算法都是基于递归的。但我找不到任何证据表明回溯不能是非递归的。那么问题是,回溯算法是否总是使用递归?
不需要使用递归就可以进行回溯。这里有一个例子:使用堆栈的非递归回溯:
boolean solve(Node n) {
put node n on the stack;
while the stack is not empty {
if the node at the top of the stack is a leaf {
if it is a goal node, return true
else pop it off the stack
}
else {
if the node at the top of the stack has untried children
push the next untried child onto the stack
else pop the node off the stack
}
return false
}
根据我的测试,非递归解法明显更快。我并不是说非递归解法总是更快,但它确实提供了更多性能优化的灵活性(你可以决定将什么放入堆栈,而不是保存整个调用栈)。
O(n)
循环,没有任何堆栈... - undefined