java中的递归

Joh*_*ino 0 java recursion

给定此方法调用:

public class MainClass {

public static void main(String[] args) {
    System.out.println(fib(3));
}

private static int fib(int i) {
     System.out.println("Into fib with i = " + i);

    if (i < 2) {
        System.out.println("We got here");
        return i;
    }
    return fib(i-1) + fib(i-2); 
}

 }
Run Code Online (Sandbox Code Playgroud)

我期望:

* fib(i-1) to return 2
* fib(i-2) to return 1
* return 2 + 1 to return 3
Run Code Online (Sandbox Code Playgroud)

结果:

2
Run Code Online (Sandbox Code Playgroud)

这是控制台的输出:

Into fib with i = 3
Into fib with i = 2
Into fib with i = 1
We got here
Into fib with i = 0
We got here
Run Code Online (Sandbox Code Playgroud)

我理解这一部分的一切:

Into fib with i = 0
Run Code Online (Sandbox Code Playgroud)

我什么时候可以0?

Ned*_*der 5

fib(3)电话fib(2).当你调用fib(2),它会调用fib(i-1)fib(i-2),那就是,fib(1)fib(0).