当前位置:网站首页>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;
}
边栏推荐
- 港科大&MSRA新研究:关于图像到图像转换,Fine-tuning is all you need
- 拼多多败诉:“砍价免费拿”侵犯知情权但不构成欺诈,被判赔400元
- 「解析」FocalLoss 解决数据不平衡问题
- 如何解决数据库插入数据显示SQLSTATE[HY000]: General error: 1364 Field ‘xxxxx‘ doesn‘t have a default value错误
- dolphinscheduler3.x本地启动
- 学术报告系列(六) - Autonomous Driving on the journey to full autonomy
- JVM 全面深入
- 学习笔记|数据小白使用DataEase制作数据大屏
- JWT certification
- VMware安装后打开就蓝屏
猜你喜欢
LM11丨重构K线构建择时交易策略
屏幕程序用串口无法调试情况
Redis(二)—Redis通用命令
Abnova 体外转录 mRNA工作流程和加帽方法介绍
偏执的非合格公司
[FPGA] EEPROM based on I2C
Matlab / envi principal component analysis implementation and result analysis
Go straight to the 2022ecdc fluorite cloud Developer Conference: work with thousands of industries to accelerate intelligent upgrading
Software testing knowledge reserve: how much do you know about the basic knowledge of "login security"?
Programmers' daily | daily anecdotes
随机推荐
MySQL(十)
[shell] summary of common shell commands and test judgment statements
ViewModelProvider.of 过时方法解决
2022 Android interview essential knowledge points, a comprehensive summary
【从零开始】win10系统部署Yolov5详细过程(CPU,无GPU)
Test the foundation of development, and teach you to prepare for a fully functional web platform environment
[solution] final app status- undefined, exitcode- 16
UIC(组态UI工程)公版文件库新增7款行业素材
安装mongodb数据库
屏幕程序用串口无法调试情况
LM small programmable controller software (based on CoDeSys) Note 23: conversion of relative coordinates of servo motor operation (stepping motor) to absolute coordinates
HKUST & MsrA new research: on image to image conversion, fine tuning is all you need
Prompt for channel security on the super-v / device defender side when installing vmmare
How to keep accounts of expenses in life
dolphinscheduler3.x本地启动
Shared memory for interprocess communication
JMeter function assistant - random value, random string, fixed value random extraction
软件测试到了35岁,真的就干不动了吗?
Force deduction 62 different paths (the number of all paths from the upper left to the lower right of the matrix) (dynamic planning)
「运维有小邓」符合GDPR的合规要求