【发布时间】:2012-08-15 17:07:40
【问题描述】:
知识有限,用C++写了2个月
在此函数中,string code 递归递减字符,直到找到基本情况 ""。我想在找到基本情况之前修剪一些路径,对于某些string code,将找不到基本情况的路径。对于修剪,我想将路径中的属性与参数int time 进行比较。这会搜索一个由 'nodeT' 组成的 trie
struct charT {
char letter;
nodeT *next;
};
struct nodeT {
bool isOperation;
bool isCode;
int time;
Vector<charT> alpha;
};
nodeT *root
usage:
string code = "12345";
int time = convertToEpoch(20120815); //my epoch function
containsCode(code, time)
bool containsCode(string code, int time)
{
if(root == NULL) return false;
else return containsCodeHelper(root, code, time);
}
bool containsCodeHelper(nodeT *w, string code, int time)
{
if(code == "") //base case: all char found
return w->isCode;
else {
if (w->isOperation && w->time != time) return false; //case 2: time check OK <- at a midpoint in the path
for(int i = 0; i < w->alpha.size(); i++) { //Loop through the leaf
if (w->alpha[i].letter == code[0]) //case 3: leaf exists
return containsCodeHelper(w->alpha[i].next, code.substr(1), time);
}
}
return false; //if no path
}
此函数在添加时间检查修剪之前运行良好,它现在循环,returns false 如果超出时间但随后从字符位置 0 以候选 string code 重新开始。
问题:1) 是一个嵌套的return false 将递归踢回到下一个调用 for 循环,2) 是否应该将时间修剪放在具有逻辑 return false 或 return 'path' 的 for 循环中, 3) 这从根本上是不是一团糟,我需要学习一个 C++ 概念
此外,发布的函数是实际函数的简化版本——我省略了时间修饰符和“跳过”路径。在过去的问题中,我发现这些“插件”会分散问题的注意力。
【问题讨论】:
-
string word?string code? -
@timrau 修正错字
string word->string code -
在您对
containsCodeHelper()的递归调用中,您从未更新参数time。你能解释一下time是什么意思吗? -
时代,或多或少;我用
containsCode电话编辑了这个问题 -
为了检查这个功能,我放置了休息点并在每次休息时跟随汽车 - 是否有这么多路径,我应该创建一个测试用例并让它去看看结果是否正确而不是步骤通过?
标签: c++ visual-studio-2008 recursion trie pruning