当前位置:网站首页>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;
}
边栏推荐
- C interview encryption program: input plaintext by keyboard, convert it into ciphertext through encryption program and output it to the screen.
- Navicat导入15G数据报错 【2013 - Lost connection to MySQL server during query】 【1153:Got a packet bigger】
- MySQL (x)
- 肿瘤免疫治疗研究丨ProSci LAG3抗体解决方案
- [start from scratch] detailed process of deploying yolov5 in win10 system (CPU, no GPU)
- How to find the literature of a foreign language journal?
- Postgresql源码(60)事务系统总结
- Party A's requirements for those who have lost 800 yuan
- Developers don't miss it! Oar hacker marathon phase III chain oar track registration opens
- Ha Qu projection dark horse posture, only half a year to break through the 1000 yuan projector market!
猜你喜欢
Three updates to build applications for different types of devices | 2022 i/o key review
JMeter function assistant - random value, random string, fixed value random extraction
[start from scratch] detailed process of deploying yolov5 in win10 system (CPU, no GPU)
港科大&MSRA新研究:关于图像到图像转换,Fine-tuning is all you need
How to keep accounts of expenses in life
matlab / ENVI 主成分分析实现及结果分析
LM11丨重构K线构建择时交易策略
How can I check the DOI number of a foreign document?
学习笔记|数据小白使用DataEase制作数据大屏
MySQL卸载文档-Windows版
随机推荐
docker-compose启动redis集群
力扣62 不同路径(从矩阵左上到右下的所有路径数量) (动态规划)
Can't you really do it when you are 35 years old?
Cloudcompare point pair selection
精准时空行程流调系统—基于UWB超高精度定位系统
雷特智能家居龙海祁:从专业调光到全宅智能,20年专注成就专业
「解析」FocalLoss 解决数据不平衡问题
拼多多败诉:“砍价免费拿”侵犯知情权但不构成欺诈,被判赔400元
Array proof during st table preprocessing
「运维有小邓」符合GDPR的合规要求
C language sorting (to be updated)
[opencv] morphological filtering (2): open operation, morphological gradient, top hat, black hat
【解决】Final app status- UNDEFINED, exitCode- 16
Abnova 体外转录 mRNA工作流程和加帽方法介绍
字符串常量与字符串对象分配内存时的区别
matlab / ENVI 主成分分析实现及结果分析
Shared memory for interprocess communication
K8s running Oracle
MySQL installation
Go straight to the 2022ecdc fluorite cloud Developer Conference: work with thousands of industries to accelerate intelligent upgrading