为什么下面的递归程序给出下面的输出

问题描述 投票:0回答:1

我试图从一开始就理解Java递归。我通过下面的例子

public static void main(String[] args) {
  threeWays(1,4);
}

public static void threeWays(int id,int n) {
  if (n >= 0) {
    System.out.println(id + "=" + n);
    threeWays(id+1,n-1);
    threeWays(id+1,n-2);
  }
}

给出输出

1=4
2=3
3=2
4=1
5=0
4=0
3=1
4=0
2=2
3=1
4=0
3=0

我最多可以理解5 = 0,但是为什么程序会超出此范围呢?为什么当n变为-1时它不停止? 4 = 0来自哪里?我什至不知道该怎么称呼这个现象,所以这个问题看起来很模糊。任何帮助,将不胜感激。

java recursion tail-recursion
1个回答
0
投票
threeWays(id+1,n-1); // when this returns,
threeWays(id+1,n-2); // ... the program still does this

您正在递归地调用函数两次。因此,在到达第一个调用的末尾之后,它会稍微松开堆栈,然后进入第二个递归。

并且从第二个调用开始,它在每一层再次分支两次。

如果这令人困惑,在调试器中逐步执行程序可能是说明性的。您可以在其中看到调用堆栈中的每一帧,包括局部变量以及它们现在位于的代码行中。

© www.soinside.com 2019 - 2024. All rights reserved.