首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >【剑指Offer】10.1 斐波那契数列

【剑指Offer】10.1 斐波那契数列

作者头像
瑞新
发布2020-12-07 14:21:42
发布2020-12-07 14:21:42
3540
举报

题目描述

求斐波那契数列的第 n 项,n <= 39。

解题思路

考虑到第 i 项只与第 i-1 和第 i-2 项有关,因此只需要存储前两项的值就能求解第 i 项

代码语言:javascript
复制
public class Solution {
    public int Fibonacci(int n) {
// 1 1 2 3 5
        if(n <= 1)
            return n;
        
        int l = 0;
        int r = 1;
        int temp = 0;
        for(int count = 2; count <= n; count++) {
           	temp = l;
            l = r;
            r = temp + r;
        }
        return r;
    }
}

由于待求解的 n 小于 40,因此可以将前 40 项的结果先进行计算,之后就能以 O(1) 时间复杂度得到第 n 项的值。

代码语言:javascript
复制
public class Solution {
    private int[] temp = new int[40];
     
    public Solution() {
        temp[0] = 0;
        temp[1] = 1;
        for(int i = 2; i < temp.length; i++) {
            temp[i] = temp[i-1] + temp[i-2];
        }
    }
    
    public int Fibonacci(int n) {
// 1 1 2 3 5
        return temp[n];
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/08/06 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目描述
  • 解题思路
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档