当前位置:网站首页>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;
}
边栏推荐
- dolphinscheduler3.x本地启动
- ICML 2022 | 探索语言模型的最佳架构和训练方法
- Pinduoduo lost the lawsuit: "bargain for free" infringed the right to know but did not constitute fraud, and was sentenced to pay 400 yuan
- Postgresql中procedure支持事务语法(实例&分析)
- Tkinter window selects PCD file and displays point cloud (open3d)
- MySQL的安装
- LM小型可编程控制器软件(基于CoDeSys)笔记二十三:伺服电机运行(步进电机)相对坐标转换为绝对坐标
- 精准时空行程流调系统—基于UWB超高精度定位系统
- [SOC FPGA] peripheral PIO button lights up
- 安装VMmare时候提示hyper-v / device defender 侧通道安全性
猜你喜欢

港科大&MSRA新研究:关于图像到图像转换,Fine-tuning is all you need

【OpenCV】形态学滤波(2):开运算、形态学梯度、顶帽、黑帽

What are the classic database questions in the interview?

string(讲解)

学术报告系列(六) - Autonomous Driving on the journey to full autonomy

「运维有小邓」符合GDPR的合规要求

Programmers' daily | daily anecdotes

Redis (II) - redis General Command

拼多多败诉:“砍价免费拿”侵犯知情权但不构成欺诈,被判赔400元

"Parse" focalloss to solve the problem of data imbalance
随机推荐
string(讲解)
Basic DOS commands
学习笔记|数据小白使用DataEase制作数据大屏
Developers don't miss it! Oar hacker marathon phase III chain oar track registration opens
Jmeter 5.5版本发布说明
反射(二)
当前发布的SKU(销售规格)信息中包含疑似与宝贝无关的字
Common problems of caching in high concurrency scenarios
[solution] final app status- undefined, exitcode- 16
【从零开始】win10系统部署Yolov5详细过程(CPU,无GPU)
Navicat importing 15g data reports an error [2013 - lost connection to MySQL server during query] [1153: got a packet bigger]
C语言整理(待更新)
FPGA课程:JESD204B的应用场景(干货分享)
CloudCompare-点对选取
Go straight to the 2022ecdc fluorite cloud Developer Conference: work with thousands of industries to accelerate intelligent upgrading
"Parse" focalloss to solve the problem of data imbalance
Postgresql中procedure支持事务语法(实例&分析)
JVM in-depth
Force deduction 62 different paths (the number of all paths from the upper left to the lower right of the matrix) (dynamic planning)
Party A's requirements for those who have lost 800 yuan