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

举报
孙中明 发表于 2022/01/23 00:49:43 2022/01/23
【摘要】 我的答案 class Solution { public int fib(int n) { int x =f(n); return x%1000000007; ...

我的答案

class Solution {
    public int fib(int n) {
        int x =f(n);
        return x%1000000007;

    }


    public int f(int n){
        if(n<0) return -1;
        if(n==0) return 0;
        if(n==1) return 1;
        else return f(n-1)+f(n-2);

    }
}


  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

(°д°)

修改后

class Solution {
    int a=0,b=1;
    int res;
    public int fib(int n) {


        if(n<0) return -1;
        else if(n==0) return 0;
        else if(n==1) return 1;
        else for(int i=1;i<n;i++){
            res = a+b;
            a=b;
            b=res%1000000007;

        }

        return res%1000000007;

    }
}


  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

优秀答案

O(1)复杂度

int f[]={0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368,75025,121393,196418,317811,514229,832040,1346269,2178309,3524578,5702887,9227465,14930352,24157817,39088169,63245986,102334155,165580141,267914296,433494437,701408733,134903163,836311896,971215059,807526948,778742000,586268941,365010934,951279875,316290802,267570670,583861472,851432142,435293607,286725742,722019349,8745084,730764433,739509517,470273943,209783453,680057396,889840849,569898238,459739080,29637311,489376391,519013702,8390086,527403788,535793874,63197655,598991529,662189184,261180706,923369890,184550589,107920472,292471061,400391533,692862594,93254120,786116714,879370834,665487541,544858368,210345902,755204270,965550172,720754435,686304600,407059028,93363621,500422649,593786270,94208912,687995182};
int fib(int n){
    return f[n];
}


  
 
  • 1
  • 2
  • 3
  • 4
  • 5

文章来源: hiszm.blog.csdn.net,作者:孙中明,版权归原作者所有,如需转载,请联系作者。

原文链接:hiszm.blog.csdn.net/article/details/121017050

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。