当谈到递归时,这是我挣扎的地方,我知道函数何时应该为真的边缘情况,但因为我还必须添加一个 return false 语句,并且在调用堆栈的深处,它确实变为真(这是检查的全部意义!),我希望最终结果为真,并且递归停止。但最终,它找到了返回 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);
}
只要足够仔细地检查您的逻辑和数据,确定您在某个时刻点击了“count == input.length()”。最好是在堆栈用完之前的某个时候 ;)
关于java - 将返回案例添加到递归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23417123/