为了概括这个问题,我从 Zelenski CS 课程讲义中借用了材料。而且,这与我的具体问题有关,因为几年前我从不同的讲师那里上课并学习了这种 C++ 方法。讲义在这里。由于我偶尔使用它,因此我对 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
}
}
}