6. 斐波那契数列

题目

大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项。n<=39

思路1

用递归求解,F0=0,F1=1,Fn=F(n-1)+F(n-2)(n>=2,n∈N*)

    /**
     * 用递归直接求解
     */
    public static int Fibonacci1(int n) {
        if (n <= 0) {
            return 0;
        }
        if (n <= 1) {
            return n;
        } else {
            return Fibonacci1(n - 1) + Fibonacci1(n - 2);
        }
    }

思路2

用迭代方法,用两个变量记录fn-1fn-2

    /**
     * 迭代方法,用两个变量记录fn-1和fn-2:
     */
    public static int Fibonacci2(int n) {
        int a = 0, b = 1, fN = 0;
        if (n <= 0) {
            return 0;
        } else if (n == 1) {
            return 1;
        } else {
            //由a和b保存中间结果
            for (int i = 2; i <= n; i++) {
                fN = a + b;
                a = b;
                b = fN;
            }
            return fN;
        }
    }

猜你喜欢

转载自blog.csdn.net/DjokerMax/article/details/82889472