斐波那契数列

原文地址:https://www.jianshu.com/p/6a7375005f89

时间限制:1秒 空间限制:32768K

题目描述

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

我的代码

class Solution {
public:
    int Fibonacci(int n) {
        if(n<=0 || n>39)
            return 0;
        if(n==1 || n==2)
            return 1;
        return Fibonacci(n-2)+Fibonacci(n-1);
    }
};

运行时间:714ms
占用内存:488k

class Solution {
public:
    int Fibonacci(int n) {
        if(n<=0 || n>39)
            return 0;
        int g=1,f=0;
        while(n--){
            g+=f;
            f=g-f;
        }
        return f;
    }
};

运行时间:3ms
占用内存:376k

原文地址:https://www.cnblogs.com/cherrychenlee/p/10780894.html