《剑指offer》系列 斐波那契数列(Java)

链接

牛客:斐波那契数列

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

思路

非常经典的一道题目,利用动态规划的思路。可以采取策略节省空间
F(n) = F(n-1) + F(n-2)

代码

牛客:

public class Solution {
    public int Fibonacci(int n) {
        if(n <= 0)
            return 0;
        if(n == 1)
            return 1;
        int first = 0;
        int second = 1;
        int res = 0;
        for(int i = 2; i <= n; i++)
        {
            res = first + second;
            first = second;
            second = res;
        }
        return res;
    }
}

LeetCode:

class Solution {
    public int fib(int n) {
        if (n == 0 || n == 1) {
            return n;
        }
        int first = 0, second = 1;
        int result = 0;
        for (int i = 2; i <= n; i++) {
            result = (first + second) % 1000000007;
            first = second;
            second = result;
        }
        return result;
    }
}

牛客和LeetCode的区别主要在于n的取值范围,LeetCode取值范围更大,需要做取模操作。

相似题

链接:509. 斐波那契数
这题和牛客那版题目类似,不需要取模。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值