算法:斐波那契数列

问题

  • 写一个函数,输入 n ,求斐波那契(Fibonacci)数列的第 n 项(即 F(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、递归,使用了hash进行存储值,减少了重复计算的消耗
class Solution {
    private static int MOD=1000000007;      //取模
    private HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
    public int fib(int n) {
        if(n<2) return n;
        if(!map.containsKey(n)){
           int result=(fib(n-1)+fib(n-2))%MOD;
            map.put(n,result);          //将每次计算的fib存起来,减少重复计算
        }
        return map.get(n);   
    }
}
//2、动态规划
class Solution{
    private static int MOD=1000000007;
    public int fib(int n){
        if(n<2) return n;               //当n为2的时候,fib=1   
        int a=0,b=0,c=1;                //a代表n=-1,b代表n=0,c代表n=1
        for(int i=2;i<=n;i++){
            a=b;
            b=c;
            c=(a+b)%MOD;
        }
        return c;
    }
}

总结

  • 两种算法都是时间复杂度O(n)
  • 第一种空间复杂度O(n),第二种O(1)
posted @ 2022-07-29 16:43  new_monkey  阅读(119)  评论(0)    收藏  举报