带有修剪搜索的递归回溯

Recursion backtracking with pruned searches

本文关键字:递归 回溯 搜索 修剪      更新时间:2023-10-16

我有一个递归函数,它解析用每个节点中的所有字符替换的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,而不是++索引。

通常,在函数调用参数中隐藏增量操作不是一种好的编码实践(至少在我看来)。这使得读取和调试代码变得困难。