【问题标题】:Confusion about boolean recursion关于布尔递归的困惑
【发布时间】:2016-01-25 13:03:14
【问题描述】:

对于这种递归方法,我绘制了一个递归跟踪来确定recTest(a,0,4) 将返回真还是假。

public class Main {

    public static boolean recTest(int[] a, int i, int j){
        if(i>=j) return true;
        else if(a[i] > a[i+1]) return false;
        return recTest(a, i+1, j);

    }

    public static void main(String[] args) {

        int[] a = {3,6,8,7,9};
        System.out.println(Main.recTest(a,0,4));
        System.out.println(Main.recTest(a,1,4));
        System.out.println(Main.recTest(a,2,4));
        System.out.println(Main.recTest(a,3,4));
        System.out.println(Main.recTest(a,4,4));
    }

}

我得到了这个(当我手工完成时):

recTest(a,0,4) calls recTest(a,1,4)
recTest(a,1,4) calls recTest(a,2,4)
recTest(a,2,4) calls recTest(a,3,4)
recTest(a,3,4) calls recTest(a,4,4)
recTest(a,4,4) returns true [base case]

因此,我认为recTest(a,0,4) 会类似地返回 true(因为递归的“最低”返回 true)。但事实并非如此。这是我画出来后收到的输出:

false
false
false
true
true

希望能解释一下这里到底发生了什么。

【问题讨论】:

  • 问题被否决而没有解释为什么......?

标签: java algorithm recursion


【解决方案1】:

你的分析在这里关闭:

recTest(a,2,4) calls recTest(a,3,4)

由于a[2] 大于a[3]recTest() 返回false 而不是再次调用自身。

您可以通过使用调试器单步执行代码来轻松发现这一点。

【讨论】:

  • 嗯,有道理。我犯了一个愚蠢的错误。感谢您的帮助!
【解决方案2】:

会发生什么:

recTest(a,0,4) calls recTest(a,1,4)
recTest(a,1,4) calls recTest(a,2,4)
recTest(a,2,4) returns false

作为 else if 语句 a[2] > a[3]8 > 7 被满足。这就是recTest(a,0,4) 最终返回false 的原因。

为了完整起见:

recTest(a,3,4) calls recTest(a,4,4)
recTest(a,4,4) returns true

【讨论】:

  • 该死,太慢了一毫秒;)
【解决方案3】:
recTest(a,0,4) in the end calls recTest(a,2,4)=>false as the condition is if(a[2]>a[3])=> 8>7 => false
recTest(a,1,4) in the end calls recTest(a,2,4)=>false 
recTest(a,2,4) if(a[2]>a[3])=> 8>7 => false
recTest(a,3,4) if(a[3]>a[4])=> 7>9(false) => recTest(a,4,4) i=j=> true
recTest(a,4,4) returns true [base case]

【讨论】:

    【解决方案4】:

    在递归之前有一个 if-else 语句,所以我认为你背后的理由是无效的。 将您的代码放入 Eclipse 或 IntelliJ 等 IDE 中,并查看每次迭代中变量的值,您会发现它非常有意义。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-14
      • 1970-01-01
      • 2011-01-16
      • 2021-09-04
      • 2019-05-17
      • 2020-03-06
      • 2016-03-16
      • 2013-07-27
      相关资源
      最近更新 更多