斐波那契数列 (递归 循环)

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


思路一:递推

public class Solution {
    public int Fibonacci(int n) {
        if (n <= 1) return n;
        int [] fibo = new int[n + 1];

        fibo[0] = 0;
        fibo[1] = 1;
        fibo[2] = 1;
        if (n >= 3)
        {
            for (int i = 3; i <= n; i++)
                fibo[i] = fibo[i -1] + fibo[i - 2];
        }
        return fibo[n];
    }
}

思路二:递归

public class Solution {
    public int Fibonacci(int n) {
        if (n <= 1)
            return n;
        else 
            return Fibonacci(n - 1) + Fibonacci(n - 2);
    }
}


你可能感兴趣的:(剑指offer)