当前位置:网站首页>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;
}
边栏推荐
- Leite smart home longhaiqi: from professional dimming to full house intelligence, 20 years of focus on professional achievements
- 缓存在高并发场景下的常见问题
- 微信小程序隐藏video标签的进度条组件
- String (explanation)
- C interview 24 (pointer) define a double array with 20 elements a
- LM small programmable controller software (based on CoDeSys) Note 23: conversion of relative coordinates of servo motor operation (stepping motor) to absolute coordinates
- 面试中有哪些经典的数据库问题?
- How to keep accounts of expenses in life
- BindingException 异常(报错)处理
- Overview of FlexRay communication protocol
猜你喜欢
"Parse" focalloss to solve the problem of data imbalance
Experience sharing of contribution of "management world"
ICML 2022 | explore the best architecture and training method of language model
雷特智能家居龙海祁:从专业调光到全宅智能,20年专注成就专业
ICML 2022 | 探索语言模型的最佳架构和训练方法
学术报告系列(六) - Autonomous Driving on the journey to full autonomy
哈趣投影黑马之姿,仅用半年强势突围千元投影仪市场!
MySQL的安装
PostgreSQL database timescaledb function time_ bucket_ Gapfill() error resolution and license replacement
Shared memory for interprocess communication
随机推荐
MySQL的安装
C interview 24 (pointer) define a double array with 20 elements a
循环肿瘤细胞——Abnova 解决方案来啦
JESD204B时钟网络
c面试 加密程序:由键盘输入明文,通过加密程序转换成密文并输出到屏幕上。
FPGA课程:JESD204B的应用场景(干货分享)
缓存在高并发场景下的常见问题
Array proof during st table preprocessing
[opencv] morphological filtering (2): open operation, morphological gradient, top hat, black hat
Abnova 膜蛋白脂蛋白体技术及类别展示
How to solve sqlstate[hy000]: General error: 1364 field 'xxxxx' doesn't have a default value error
tkinter窗口选择pcd文件并显示点云(open3d)
UIC(组态UI工程)公版文件库新增7款行业素材
港科大&MSRA新研究:关于图像到图像转换,Fine-tuning is all you need
程序员的日常 | 每日趣闻
Learning notes | data Xiaobai uses dataease to make a large data screen
dolphinscheduler3. X local startup
String (explanation)
Experience sharing of contribution of "management world"
【OpenCV】形态学滤波(2):开运算、形态学梯度、顶帽、黑帽