《剑指offer》面试题10- I. 斐波那契数列

问题描述

写一个函数,输入 n ,求斐波那契(Fibonacci)数列的第 n 项。斐波那契数列的定义如下:

F(0) = 0,   F(1) = 1
F(N) = F(N - 1) + F(N - 2), 其中 N > 1.
斐波那契数列由 0 和 1 开始,之后的斐波那契数就是由之前的两数相加而得出。

答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。

 

示例 1:

输入:n = 2
输出:1
示例 2:

输入:n = 5
输出:5
 

提示:

0 <= n <= 100

代码1

class Solution {
public:
    int fib(int n) {
        if(n < 2) return n;
        return fib(n-1)+fib(n-2);
    }
};

结果会超出时间限制

代码2

不取余在n=45就错了,至于为啥取这个,我有很多小问号。

class Solution {
public:
    int fib(int n) {
        if(n < 2)return n;
        vector<int> num(n+1,-1);
        num[0]=0;num[1]=1;
        return comp(n,num);
    }
    int comp(int n,vector<int> &num)
    {
        if(num[n]==-1)
          num[n] = (comp(n-1,num)+comp(n-2,num))%1000000007;
        return num[n];
    }
};

结果:

执行用时 :0 ms, 在所有 C++ 提交中击败了100.00%的用户
内存消耗 :6.2 MB, 在所有 C++ 提交中击败了100.00%的用户

代码3(动态规划)

class Solution {
public:
    int fib(int n) {
        if(n < 2)return n;
        vector<int> ans(n+1,0);
        ans[0]=0;ans[1]=1;
        for(int i = 2; i <= n; ++i)
        {
            ans[i] = (ans[i-1]+ans[i-2])%1000000007;
        }
        return ans[n];
    }
    
};

结果:

执行用时 :4 ms, 在所有 C++ 提交中击败了45.29%的用户
内存消耗 :6.3 MB, 在所有 C++ 提交中击败了100.00%的用户

代码4(改进动态规划)

class Solution {
public:
    int fib(int n) {
        if(n < 2)return n;
        int n1 = 0,n2 = 1,ans;
        for(int i = 2; i <= n; ++i)
        {
            ans = (n1+n2)%1000000007;
            n1 = n2;
            n2 = ans;
        }
        return ans;
    }
    
};

结果:

执行用时 :0 ms, 在所有 C++ 提交中击败了100.00%的用户
内存消耗 :6 MB, 在所有 C++ 提交中击败了100.00%的用户
posted @ 2020-04-11 11:40  曲径通霄  阅读(106)  评论(0编辑  收藏  举报