【发布时间】:2020-02-10 12:45:24
【问题描述】:
我有一个递归函数,它解析一个 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);。为什么会发生?它是如何修复的?
我认为当遇到路径的尽头时,它正在通过函数回溯。我不想让它倒退。我检查了调用堆栈和设置中断,但这似乎是一个概念问题而不是错误。我还阅读了关于递归的教科书章节和 Wikipedia 页面——我了解回溯的概念,但不了解这种特定情况下的实现(或期望的缺乏)。我使用回溯来构建 trie 数据库,它在那里工作,但这与这里的不同,我无法弄清楚。
【问题讨论】:
-
我在每个递归调用中添加了 return -->
return suggestCorrections(w->alpha[index].next, ... );而且,现在它不会回溯——我真的很想了解我在这里做什么。黑客解决方案与这个怎么样似乎有点粗略。
标签: c++ visual-studio-2008 recursion backtracking