[英]adding return case to recursive function
说到递归,这里是我挣扎的地方,我知道函数应该为true的边缘情况,但是因为我必须添加一个返回false语句,并且在调用堆栈的某个深处,它确实变为true (这是检查的全部要点!),我希望最终结果是真实的,并且让递归停止。 但最终,它找到了返回false的方法,仅仅因为它是函数的最后一件事。
public boolean isPathHelper(Node node, String input){
if(node.accept == true){
return true;
}else{
if(input.length() == 0){
return false;
}
isPathHelper(getNextState(node, input.charAt(0) -'0'), input.substring(1));
return false;
}
我该如何处理这种情况? 我知道全局变量可以提供帮助,但我希望我的知识存在差距。
尝试这个:
public boolean isPathHelper(Node node, String input, int count){
if(input.length() == 0){
return false; //I can't go any further: return "failed"
}
else if(count == input.length()){
return true; //if I ever reach here, then I am done: return "success"
}
// else call self recursively
return isPathHelper(
getNextState(node, input.charAt(0) -'0'), input.substring(1), count+1);
}
观察一下你的逻辑和数据不够仔细,以确保你打“计数== input.length()”在某些时候。 最好在你用完堆栈之前的某个时候;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.