带有修剪搜索的递归回溯
Recursion backtracking with pruned searches
我有一个递归函数,它解析用每个节点中的所有字符替换的trie字符串数据库。在递归调用中,增加编辑计数,然后测试新字符串:1)如果所有节点都已解析,2)如果字符串等于已批准字符串列表中的字符串。因此,结果应该是测试字符串和数据库中所有可能的字符串之间的编辑距离。
void suggestCorrections(nodeT *w, Set<CorrectionT> &suggest, int index, string test, string final, double edits)
{
if (word == "") {
if (containsCode(final)) //compare with list of approved strings
updateSet(w, suggest, final, edits);
} else { //continue to search path
if( w->alpha.size() > index) {
if (test[0] == w->alpha[index].char)
suggestCorrections(w->alpha[index].next, suggest, 0, test.substr(1), final+test[0], edits); //follow matching char
suggestCorrections(w, suggest, ++index, test, final, edits);//check next path
suggestCorrections(w->alpha[index].next, suggest, 0, test.substr(1), final+w->alpha[index].char, ++edits);//follow path
}
}
}
struct CorrectionT {
double editDistance; //stackItems
string suggestedWord; //stackItems
string suggestDescription;
string gates;
};
问题是,当w->alpha size()等于index时,路径正确结束,但当index递增超过w->alpha结束时,会输入最后一个路径suggestCorrections(w->alpha[index].next, suggest, 0, test.substr(1), final+w->alpha[index].char, ++edits);
。为什么会发生这种情况?它是如何修复的?
我认为这是在满足路径末端时回溯函数。我不希望它倒退。我检查了整个调用堆栈和设置中断,但这似乎是一个概念问题,而不是一个bug。我还阅读了关于递归的教科书章节和维基百科页面——我理解回溯的概念,但不理解在这种特定情况下的实现(或期望的缺乏)。我使用回溯来构建trie数据库,它在那里起到了作用,但与这里的不同之处在于,我无法理解这一点。
在对suggestCorrection的倒数第二个调用中,您正在传递++索引。这是递增index的值,然后在最后一次调用suggestCorrections时传递该值。我还没有真正尝试理解您的代码,但看起来您可能只是想在倒数第二次调用中传递索引+1,而不是++索引。
通常,在函数调用参数中隐藏增量操作不是一种好的编码实践(至少在我看来)。这使得读取和调试代码变得困难。
相关文章:
- 通过递归进行因子分解
- 返回不停止函数,递归函数问题?(编程练习,动态规划,Levenshtein 回溯)
- C++ 使用递归回溯的数独求解器不起作用
- 国际象棋骑士巡回赛使用递归回溯
- 递归回溯打印长度为N的二进制数的所有组合,而不使用循环
- 使用C 中的递归对迷宫进行回溯
- C 中的递归回溯
- C 递归回溯
- 使用队列的非递归回溯:内存不足
- sudoku递归回溯,未提早编译
- 保存使用递归回溯找到的最佳路径
- 带有修剪搜索的递归回溯
- 如何使用void类型处理递归回溯返回
- 使用回溯和递归 c++ 的八皇后
- 使用回溯递归 C++
- 用回溯理论递归求解一个数独难题
- 使用递归和回溯生成所有可能的组合
- 递归回溯数独求解问题,c++
- 启发式算法在递归回溯中的应用
- 深度优先搜索或回溯递归查找字谜/拼字板中所有可能的字母组合