当前位置:网站首页>leetcode 509. Fibonacci number
leetcode 509. Fibonacci number
2022-07-07 07:06:00 【Blue feather birds】
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.
The famous Fibonacci Numbers ,F(0)=0, F(1)=1,
Followed by the sum of the first two numbers , Please n individual Fibonacci Numbers .
Ideas :
DP
It can be recorded with a one-dimensional array 0~n individual Fibonacci Numbers , Then the first i One number is F(i-2)+F(i-1),
But because only the first two are used , So just save it with two numbers .
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;
}
边栏推荐
猜你喜欢
ANR 原理及实践
Config distributed configuration center
Use of completable future
健身房如何提高竞争力?
父组件传递给子组件:Props
.net core 访问不常见的静态文件类型(MIME 类型)
What books can greatly improve programming ideas and abilities?
MySQL的主从复制原理
Basic introduction of JWT
. Net 5 fluentftp connection FTP failure problem: this operation is only allowed using a successfully authenticated context
随机推荐
Answer to the second stage of the assignment of "information security management and evaluation" of the higher vocational group of the 2018 Jiangsu Vocational College skills competition
[GNN] graphic gnn:a gender Introduction (including video)
jdbc数据库连接池使用问题
LC 面试题 02.07. 链表相交 & LC142. 环形链表II
使用TCP/IP四层模型进行网络传输的基本流程
联合索引ABC的几种索引利用情况
大促过后,销量与流量兼具,是否真的高枕无忧?
MOS tube parameters μ A method of Cox
2022/07/04学习记录
How DHCP router works
[noi simulation] regional division (conclusion, structure)
After the promotion, sales volume and flow are both. Is it really easy to relax?
场馆怎么做体育培训?
Use of completable future
精准时空行程流调系统—基于UWB超高精度定位系统
ANR 原理及实践
Basic process of network transmission using tcp/ip four layer model
Get the city according to IP
ESXI挂载移动(机械)硬盘详细教程
Initial experience of addresssanitizer Technology