剑指offer_斐波那契数列

package solution;

public class Fibonacci {
    /*
     *  f(n) = f(n-1) + f(n-2) n>1
     *  f(0) = 0
     *  f(1) = 1
     * */
    public static void main(String[] args) {
        System.out.println(Fibonacci(3));
    }

    public static int Fibonacci(int n) {
        if (n == 0 || n == 1) {
            return n;
        }
        int[] a = new int[n + 1];
        a[0] = 0;
        a[1] = 1;
        for (int i = 2; i <= n; i++) {
            a[i] = a[i - 1] + a[i - 2];
        }
        return a[n];
    }

    public static int Fibonacci_2(int n) {
        if (n == 0 || n == 1) {
            return n;
        }
        int fibNMinusOne = 1;
        int fibNMinusTwo = 0;
        int fibN = 0;              //不用数组保存可以节约空间
        for (int i = 2; i <= n; i++) {
            fibN = fibNMinusOne + fibNMinusTwo;
            fibNMinusOne = fibN;
            fibNMinusTwo = fibNMinusOne;
        }
        return fibN;
    }
}

 

posted @ 2019-08-21 15:55  Practical  阅读(131)  评论(0编辑  收藏  举报