斐波拉契數的幾種求法

斐波拉契數列求法的題目有:

  • 509 斐波拉契
  • 面試題10-1 斐波拉契數列
  • 70 爬樓梯
解法一:

傻遞歸

public class Solution {
    public int fib(int N) {
        if (N < 2) return N;
        return fib(N - 1) + fib(N - 2);
    }
}
解法二:

帶緩存的遞歸

public class Solution {

    //緩存
    static int[] cache;

    public int fib(int N) {
        //初始化緩存
        cache = new int[N + 1];
        return myfib(N);
    }

    public int myfib(int n) {
        //退出條件
        if (n <= 1) {
            cache[n] = n;
            return cache[n];
        }
        //如果不存在就遞歸調用存入緩存
        if (cache[n] == 0){
            cache[n] = myfib(n-1)+myfib(n-2);
        }
        return cache[n];
    }
}
解法三

迭代法:

public class Solution {
    public int fib(int n) {
        if (n < 2) {
            return n;
        }
        int f0 = 0;
        int f1 = 1;
        int f2 = 0;

        for (int i = 2; i <= n; i++) {
            f2 = f0 + f1;
            f0 = f1;
            f1 = f2;
        }
        return f2;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章