剑指Offer-斐波那契数列

斐波那契数列

题目

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

思路

1.递归
2.动态规划,保存中间值

代码

public int Fibonacci_i(int n){
    return Fibonacci_i(n-1)+Fibonacci_i(n-2);
}

public int Fibonacci_ii(int n){
    if (n<=0){
        return 0;
    }

    if (n==1||n==2){
        return 1;
    }
    int Prepre=1;
    int pre=1;
    int current=0;
    for (int i=3;i<n;i++){
        current = Prepre+pre;
        Prepre = pre;
        pre = current;
    }

    return current;
}
0%