【发布时间】:2012-08-02 18:11:17
【问题描述】:
为了概括这个问题,我从 Zelenski CS 课程讲义中借用了材料。而且,这与我的具体问题有关,因为几年前我从不同的讲师那里上课并学习了这种 C++ 方法。讲义是here。由于我偶尔使用它,因此我对 C++ 的理解很低。基本上,我需要编写程序的几次我回到课堂资料,找到类似的东西并从那里开始。
在这个例子中(第 4 页),Julie 在字符串函数中使用递归算法查找单词。为了减少递归调用的数量,她添加了一个决策点bool containsWord()。
string FindWord(string soFar, string rest, Lexicon &lex)
{
if (rest.empty()) {
return (lex.containsWord(soFar)? soFar : "");
} else {
for (int i = 0; i < rest.length(); i++) {
string remain = rest.substr(0, i) + rest.substr(i+1);
string found = FindWord(soFar + rest[i], remain, lex);
if (!found.empty()) return found;
}
}
return ""; // empty string indicates failure
}
为了增加该算法的使用灵活性,是否可以将其实现为 void 类型?
void FindWord(string soFar, string rest, Lexicon &lex, Set::StructT &words)
{
if (rest.empty()) {
if (lex.containsWord(soFar)) //this is a bool
updateSet(soFar, words); //add soFar to referenced Set struct tree
} else {
for (int i = 0; i < rest.length(); i++) {
string remain = rest.substr(0, i) + rest.substr(i+1);
return FindWord(soFar + rest[i], remain, lex, words); //<-this is where I am confused conceptually
}
}
return; // indicates failure
}
还有,没有回报怎么办
void FindWord(string soFar, string rest, Lexicon &lex, Set::StructT &words)
{
if (rest.empty()) {
if (lex.containsWord(soFar))
updateSet(soFar, words); //add soFar to Set memory tree
} else {
for (int i = 0; i < rest.length(); i++) {
string remain = rest.substr(0, i) + rest.substr(i+1);
FindWord(soFar + rest[i], remain, lex, words); //<-this is where I am confused conceptually
}
}
}
【问题讨论】:
标签: c++ recursion void backtracking recursive-backtracking