当前位置:网站首页>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;
}
边栏推荐
- MySQL的安装
- JVM 全面深入
- Software testing knowledge reserve: how much do you know about the basic knowledge of "login security"?
- 一段程序让你明白什么静态内部类,局部内部类,匿名内部类
- Overview of FlexRay communication protocol
- FPGA课程:JESD204B的应用场景(干货分享)
- 二十岁的我4面拿到字节跳动offer,至今不敢相信
- JWT 认证
- PostgreSQL database timescaledb function time_ bucket_ Gapfill() error resolution and license replacement
- Redis(一)——初识Redis
猜你喜欢

How to keep accounts of expenses in life

Experience sharing of contribution of "management world"

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

PostgreSQL database timescaledb function time_ bucket_ Gapfill() error resolution and license replacement

Cloudcompare point pair selection

FlexRay通信协议概述

Several key steps of software testing, you need to know

ICML 2022 | explore the best architecture and training method of language model

二十岁的我4面拿到字节跳动offer,至今不敢相信
![[SOC FPGA] peripheral PIO button lights up](/img/34/58728bddbf91eb69e9c0062dbfd531.jpg)
[SOC FPGA] peripheral PIO button lights up
随机推荐
c语言(结构体)定义一个User结构体,含以下字段:
Which foreign language periodicals are famous in geology?
基于FPGA的VGA协议实现
Tkinter window selects PCD file and displays point cloud (open3d)
Several key steps of software testing, you need to know
Overview of FlexRay communication protocol
c语言面试写一个函数在字符串N中查找第一次出现子串M的位置。
肿瘤免疫治疗研究丨ProSci LAG3抗体解决方案
ceres-solver和g2o性能比较
Navicat importing 15g data reports an error [2013 - lost connection to MySQL server during query] [1153: got a packet bigger]
ETCD数据库源码分析——从raftNode的start函数说起
ICML 2022 | 探索语言模型的最佳架构和训练方法
Unity C# 函数笔记
Leite smart home longhaiqi: from professional dimming to full house intelligence, 20 years of focus on professional achievements
ST表预处理时的数组证明
Google Chrome browser released patch 103.0.5060.114 to fix the 0-day vulnerability
学术报告系列(六) - Autonomous Driving on the journey to full autonomy
VIM mapping large K
Etcd database source code analysis -- starting from the start function of raftnode
Install mongodb database