当前位置:网站首页>leetcode 剑指 Offer 10- I. 斐波那契数列
leetcode 剑指 Offer 10- I. 斐波那契数列
2022-07-30 08:52:00 【kt1776133839】
题目描述:
写一个函数,输入 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
解题思路:
动态规划:
状态定义: 设 dp为一维数组,其中 dp[i] 的值代表 斐波那契数列第 i 个数字 。
转移方程: dp[i+1]=dp[i]+dp[i−1] ,即对应数列定义 f(n+1)=f(n)+f(n−1);
初始状态: dp[0]=0, dp[1]=1 ,即初始化前两个数字;
返回值: dp[n] ,即斐波那契数列的第 n 个数字。
求余运算规则: 设正整数 x,y,p ,求余符号为 ⊙ ,则有 (x+y)⊙p=(x⊙p+y⊙p)⊙p。
Java程序:
class Solution {
public int fib(int n) {
int a = 0, b = 1, sum;
for(int i = 0; i < n; i++){
sum = (a + b) % 1000000007;
a = b;
b = sum;
}
return a;
}
}
边栏推荐
- Apache DolphinScheduler新一代分布式工作流任务调度平台实战-上
- Concise Notes on Integrals - Types of Curve Integrals of the First Kind
- How to implement Golang DES encryption and decryption?
- It is said that FPGA is high-end, what can it do?
- MySQL Explain usage and parameter detailed explanation
- 读书笔记:《这才是心理学:看穿伪心理学的本质(第10版)》
- ClickHouse
- PyQt5快速开发与实战 8.1 窗口风格
- Integral Special Notes - Definition of Integral
- ant-design form form verification upload component (with personal packaged upload component)
猜你喜欢
随机推荐
conda 导出/导出配置好的虚拟环境
2022 Hangzhou Electric Multi-School 2nd Game
els 方块停在方块上。
HCIP --- MPLS VPN实验
分布式系统大势所趋,银行运维如何与时俱进?
Excel xlsx file not supported两种解决办法【杭州多测师】【杭州多测师_王sir】
C语言经典练习题(3)——“汉诺塔(Hanoi)“
PyQt5快速开发与实战 8.1 窗口风格
初识Apifox——如何使用Apifox做一个简单的接口测试
ACL 2022 | Introduce angular margin to construct comparative learning objectives and enhance text semantic discrimination ability
实施敏捷过程中这些常见的问题你可曾遇到?
Oracle 创建和操作表
回板后,处理器不启动,怎么办?
69. Sqrt(x)x 的平方根
BaseQuickAdapter方法getBindingAdapterPosition
瑞吉外卖项目(五) 菜品管理业务开发
【零基础玩转BLDC系列】以GD32F30x为例定时器相关功能详解
硬件工程师
Activating data potential Amazon cloud technology reshapes cloud storage "family bucket"
Network/Information Security Top Journal and Related Journals Conference









