递归调用次数

Pit*_*998 5 java recursion

如何更改算法以进一步显示递归调用的数量?

public class fibb {

    static long fibonacci(long n){
        if (n == 0)
            return 0;
        else if (n == 1)
            return 1;
        else
            return fibonacci(n - 1) + fibonacci(n - 2);
    }

    public static void main(String[] args){
        System.out.println(fibonacci(14));
    }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*oun 0

静态变量仅初始化一次,因此您可以创建一个静态计数器变量,在递归的第一行将其加 1:

public class fibb {

    private static int numberOfCalls = 0;

    static long fibonacci(long n){
        numberOfCalls++;
        if (n == 0)
            return 0;
        else if (n == 1)
            return 1;
        else
            return fibonacci(n - 1) + fibonacci(n - 2);
    }

    public static void main(String[] args){
        System.out.println(fibonacci(14));
        //numberOfCalls is the number of the calls to the recursion
    }
}
Run Code Online (Sandbox Code Playgroud)