当前位置:网站首页>leetcode 509. Fibonacci Number(斐波那契数字)
leetcode 509. Fibonacci Number(斐波那契数字)
2022-07-07 02:17:00 【蓝羽飞鸟】
The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,
F(0) = 0, F(1) = 1
F(n) = F(n - 1) + F(n - 2), for n > 1.
Given n, calculate F(n).
Example 1:
Input: n = 2
Output: 1
Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.
Example 2:
Input: n = 3
Output: 2
Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.
著名的Fibonacci数字,F(0)=0, F(1)=1,
后面依次是前两个数字的和,求第n个Fibonacci数字。
思路:
DP
可以用一维数组记录下0~n个Fibonacci数字,然后第i个数字就是F(i-2)+F(i-1),
但是因为只用到前两个,所以只需要用两个数字保存就行了。
public int fib(int n) {
if(n == 0) return 0;
if(n == 1) return 1;
int n1 = 0;
int n2 = 1;
for(int i = 2; i <= n; i ++) {
int tmp = n1 + n2;
n1 = n2;
n2 = tmp;
}
return n2;
}
边栏推荐
猜你喜欢

LM小型可编程控制器软件(基于CoDeSys)笔记二十三:伺服电机运行(步进电机)相对坐标转换为绝对坐标

直击2022ECDC萤石云开发者大会:携手千百行业加速智能升级

Leite smart home longhaiqi: from professional dimming to full house intelligence, 20 years of focus on professional achievements

string(讲解)

雷特智能家居龙海祁:从专业调光到全宅智能,20年专注成就专业

Redis(二)—Redis通用命令

Prompt for channel security on the super-v / device defender side when installing vmmare

Abnova循环肿瘤DNA丨全血分离,基因组DNA萃取分析

Experience sharing of contribution of "management world"

Go straight to the 2022ecdc fluorite cloud Developer Conference: work with thousands of industries to accelerate intelligent upgrading
随机推荐
「解析」FocalLoss 解决数据不平衡问题
Common problems of caching in high concurrency scenarios
JVM in-depth
MySQL的安装
How to use wechat cloud hosting or cloud functions for cloud development of unapp development applet
项目实战 五 拟合直线 获得中线
Force deduction 62 different paths (the number of all paths from the upper left to the lower right of the matrix) (dynamic planning)
dolphinscheduler3. X local startup
学术报告系列(六) - Autonomous Driving on the journey to full autonomy
How to keep accounts of expenses in life
LM11丨重构K线构建择时交易策略
Matlab / envi principal component analysis implementation and result analysis
Postgresql源码(60)事务系统总结
MySQL(十)
LM小型可编程控制器软件(基于CoDeSys)笔记二十三:伺服电机运行(步进电机)相对坐标转换为绝对坐标
「运维有小邓」符合GDPR的合规要求
2022 Android interview essential knowledge points, a comprehensive summary
Apache ab 压力测试
Kotlin之 Databinding 异常
Abnova 膜蛋白脂蛋白体技术及类别展示