当前位置:网站首页>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;
}
边栏推荐
- Markdown displays pictures side by side
- Three updates to build applications for different types of devices | 2022 i/o key review
- 博士申请 | 上海交通大学自然科学研究院洪亮教授招收深度学习方向博士生
- [solution] final app status- undefined, exitcode- 16
- Apache ab 压力测试
- How can I check the DOI number of a foreign document?
- Problems and precautions about using data pumps (expdp, impdp) to export and import large capacity tables in Oracle migration
- VMware安装后打开就蓝屏
- Kotlin之 Databinding 异常
- Ant manor safety helmet 7.8 ant manor answer
猜你喜欢

Which foreign language periodicals are famous in geology?

ETCD数据库源码分析——从raftNode的start函数说起

LM小型可编程控制器软件(基于CoDeSys)笔记二十三:伺服电机运行(步进电机)相对坐标转换为绝对坐标

Test the foundation of development, and teach you to prepare for a fully functional web platform environment

面试中有哪些经典的数据库问题?

基于FPGA的VGA协议实现

Handling hardfault in RT thread

Redis (I) -- getting to know redis for the first time

Common problems of caching in high concurrency scenarios

Abnova循环肿瘤DNA丨全血分离,基因组DNA萃取分析
随机推荐
港科大&MSRA新研究:关于图像到图像转换,Fine-tuning is all you need
Go straight to the 2022ecdc fluorite cloud Developer Conference: work with thousands of industries to accelerate intelligent upgrading
偏执的非合格公司
How to solve sqlstate[hy000]: General error: 1364 field 'xxxxx' doesn't have a default value error
C language interview to write a function to find the first public string in two strings
请问如何查一篇外文文献的DOI号?
MySQL的安装
[FPGA] EEPROM based on I2C
安装VMmare时候提示hyper-v / device defender 侧通道安全性
JWT certification
Several key steps of software testing, you need to know
Common problems of caching in high concurrency scenarios
LM small programmable controller software (based on CoDeSys) Note 23: conversion of relative coordinates of servo motor operation (stepping motor) to absolute coordinates
C interview encryption program: input plaintext by keyboard, convert it into ciphertext through encryption program and output it to the screen.
Array proof during st table preprocessing
地质学类比较有名的外文期刊有哪些?
Which foreign language periodicals are famous in geology?
MySQL(十)
途家、木鸟、美团……民宿暑期战事将起
c语言面试写一个函数在字符串N中查找第一次出现子串M的位置。