当前位置:网站首页>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;
}
边栏推荐
- Wechat applet hides the progress bar component of the video tag
- 基本Dos命令
- Matlab / envi principal component analysis implementation and result analysis
- Abnova 免疫组化服务解决方案
- How to keep accounts of expenses in life
- 怎样查找某个外文期刊的文献?
- 途家、木鸟、美团……民宿暑期战事将起
- MySQL卸载文档-Windows版
- 2022Android面试必备知识点,一文全面总结
- ICML 2022 | explore the best architecture and training method of language model
猜你喜欢

二十岁的我4面拿到字节跳动offer,至今不敢相信

How can I check the DOI number of a foreign document?

程序员的日常 | 每日趣闻

2022 Android interview essential knowledge points, a comprehensive summary

Common problems of caching in high concurrency scenarios

开发者别错过!飞桨黑客马拉松第三期链桨赛道报名开启

matlab / ENVI 主成分分析实现及结果分析

缓存在高并发场景下的常见问题

Implementation of VGA protocol based on FPGA

Leite smart home longhaiqi: from professional dimming to full house intelligence, 20 years of focus on professional achievements
随机推荐
LM small programmable controller software (based on CoDeSys) Note 23: conversion of relative coordinates of servo motor operation (stepping motor) to absolute coordinates
VMware安装后打开就蓝屏
How to use wechat cloud hosting or cloud functions for cloud development of unapp development applet
Three updates to build applications for different types of devices | 2022 i/o key review
c语言面试写一个函数在字符串N中查找第一次出现子串M的位置。
docker-compose启动redis集群
博士申请 | 上海交通大学自然科学研究院洪亮教授招收深度学习方向博士生
Redis (II) - redis General Command
线性代数(一)
VIM mapping large K
How to find the literature of a foreign language journal?
面试中有哪些经典的数据库问题?
微信小程序隐藏video标签的进度条组件
c语言(结构体)定义一个User结构体,含以下字段:
怎样查找某个外文期刊的文献?
POI export to excel: set font, color, row height adaptation, column width adaptation, lock cells, merge cells
Party A's requirements for those who have lost 800 yuan
FPGA课程:JESD204B的应用场景(干货分享)
Handling hardfault in RT thread
缓存在高并发场景下的常见问题