java - 将返回案例添加到递归函数

标签 java algorithm recursion

当谈到递归时,这是我挣扎的地方,我知道函数何时应该为真的边缘情况,但因为我还必须添加一个 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/

相关文章:

java - 找不到适合 jdbc :oracle:thin:@localhost:1521:XE when running web application 的驱动程序

java - 如何在 Java 中格式化具有多个日期的字符串

algorithm - 以下代码片段的时间复杂度?

php - 计算总页面浏览量的更好方法?

algorithm - 复杂性算法分析与 if

algorithm - 具有递归函数的解决方案

C++ 元编程热切求值

java - TextViews 没有占用 View 中设置的layout_weight

java - 如何监控 iOS/Android 设备中的 https/ssl 流量

java - 方法调用自身..递归?