首页 > 其他分享 >剑指 Offer 10- I. 斐波那契数列

剑指 Offer 10- I. 斐波那契数列

时间:2022-08-21 12:11:51浏览次数:82  
标签:10 数列 int 复杂度 斐波 那契 dp

一、题目

  写一个函数,输入 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:

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

输入:n = 5
输出:5
 

提示:

0 <= n <= 100

 

二、分析与代码

  使用最朴素的递归会超时,因此可以考虑其他方法。

  (1)动态规划:边界条件是0和1,转移方程为:dp[i] = dp[i-1] + dp[i-2]。但是时间复杂度和空间复杂度都是O(n).

class Solution {
    public int fib(int n) {
        int[] dp = new int [111];
        dp[0] = 0;
        dp[1] = 1;
        for(int i=2;i<=n;i++){
            dp[i] = (dp[i-1] + dp[i-2])%1000000007;
        }
        return dp[n];
    }
}

  时间复杂度:O(n),循环n次,每次只做一个操作。

  空间复杂度:O(n),循环n次,每一次都要存储算到的和。

  (2)F(n) 只和 F(n-1)F(n−1) 与 F(n-2)F(n−2) 有关,因此可以使用「滚动数组思想」把空间复杂度优化成 O(1)。

 

 

class Solution {
    public int fib(int n) {
        if(n<2) return n;
        int p=0,q=0,s=1;
        for(int i=2;i<=n;i++){
            p=q;
            q=s;
            s=(p+q)%1000000007;
        }
        return s;
    }
}

  时间复杂度:O(n)

  空间复杂度:O(1),只需p,q,s三个额外空间。

 

 

标签:10,数列,int,复杂度,斐波,那契,dp
From: https://www.cnblogs.com/lxpblogs/p/16609753.html

相关文章

  • ceph 010 clustermap ceph调优
    clustermap[ceph:root@clienta/]#cephmondumpepoch4fsid2ae6d05a-229a-11ec-925e-52540000fa0clast_changed2021-10-01T09:33:53.880442+0000created2021......
  • Visual AssistX (x64) Version 10.9.2458 Cracked
    说明1.只支持VisualAssistXx64的2458版本2.只支持VisualStudio2022版本3.出现错误提示说明安装的Vax版本不对。声明敬请各位大爷:如果之前使用过其他破解版......
  • Day10-CSS
    图片整合,精灵图,雪碧图:什么是图片整合: 1.把小的图片整合到一个大的图片上为什么要图片整合: 优点: 较少对服务器的请求次数 减少图片的内存 增加页面的加载速度 ......
  • jmeter-10-提取多个id拼接请求数据及日期时间偏移,你会了吗?
    前言平时在使用Jmeter过程中,可能会遇到各种需求的参数需要处理,比如提取id拼接数组,又如时间日期处理等等那么接下来将记录平时个人使用时遇到过挺多的场景!gogogo!一、......
  • [Google] LeetCode 1048 Longest String Chain
    YouaregivenanarrayofwordswhereeachwordconsistsoflowercaseEnglishletters.\(word_A\)isapredecessorof\(word_B\)ifandonlyifwecaninserte......
  • PAT Advanced 1036 Boys vs Girls(25)
    题目描述:Thistimeyouareaskedtotellthedifferencebetweenthelowestgradeofallthemalestudentsandthehighestgradeofallthefemalestudents.Inp......
  • PAT Advanced 1035 Password(20)
    题目描述:ToprepareforPAT,thejudgesometimeshastogeneraterandompasswordsfortheusers.Theproblemisthattherearealwayssomeconfusingpasswords......
  • PAT Advanced 1027 Colors in Mars(20)
    题目描述:PeopleinMarsrepresentthecolorsintheircomputersinasimilarwayastheEarthpeople.Thatis,acolorisrepresentedbya6-digitnumber,wher......
  • PAT Advanced 1019 General Palindromic Number(20)
    题目描述:AnumberthatwillbethesamewhenitiswrittenforwardsorbackwardsisknownasaPalindromicNumber.Forexample,1234321isapalindromicnumber......
  • PAT Advanced 1021 Deepest Root(25)
    题目描述:Agraphwhichisconnectedandacycliccanbeconsideredatree.Theheightofthetreedependsontheselectedroot.Nowyouaresupposedtofindthe......