Three Realization Methods of Fibonacci Sequence

1. A very inefficient solution

public static long fibonacci1(int n) {
    
    
        if (n <= 0) return 0;
        if (n == 1) return 1;
        return fibonacci1(n-1) + fibonacci1(n-2);
    }

Disadvantages: In the process of recursive solution, many nodes are repeated, and the number of repeated nodes will increase sharply as n increases, which means that the amount of calculation will increase sharply as n increases.

2. Ways to avoid duplicate nodes

Calculating from bottom to top, first calculate f(2) based on f(0) and f(1), f(1) and f(2) calculate f(3)... and so on, you can calculate the nth term , The time complexity is O(n).

public static long fibonacci2(int n) {
    
    
        if (n == 1 || n == 2) return  1;
        long fibNMinusOne = 1;  // 用来记录计算项的前面的前面的数
        long fibNMinusTwo = 1;  // 用来记录当前计算项的前一项
        long fibN = 0;          //用来记录结果
        for (int i = 2; i < n; i++) {
    
    
            fibN = fibNMinusOne + fibNMinusTwo;
            fibNMinusTwo = fibNMinusOne;
            fibNMinusOne = fibN;
        }
        return fibN;
    }

3. The time complexity is O(logn) but not practical enough

    public static int fibonacci3(int n) {
    
    
        if (n == 0) return 1;
        if (n == 1) return 1;
        //n为偶数
        if (n % 2 == 0) return fibonacci3(n / 2) * fibonacci3(n / 2) + fibonacci3(n / 2 - 1) * fibonacci3(n / 2 - 1);
        //n为奇数
        else return fibonacci3(n / 2) * fibonacci3(n / 2 + 1) + fibonacci3(n / 2 - 1) * fibonacci3(n / 2);
    }

Guess you like

Origin blog.csdn.net/Zmd_23/article/details/108741759