当前位置:网站首页>力扣:509. 斐波那契数
力扣:509. 斐波那契数
2022-08-04 05:14:00 【empty__barrel】
力扣:509. 斐波那契数
斐波那契数 (通常用 F(n) 表示)形成的序列称为 斐波那契数列 。该数列由 0 和 1 开始,后面的每一项数字都是前面两项数字的和。也就是:
F(0) = 0,F(1) = 1
F(n) = F(n - 1) + F(n - 2),其中 n > 1
给定 n ,请计算 F(n) 。
普通代码:
class Solution {
public:
int fib(int N) {
if (N <= 1) return N;
vector<int> dp(N + 1);
dp[0] = 0;
dp[1] = 1;
for (int i = 2; i <= N; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[N];
}
};
代码:其实只需要维护两个数值即可
class Solution {
public:
int fib(int n) {
if(n<=1) return n;
int dp[2];
dp[0] = 0;
dp[1] = 1;
for(int i = 2; i <= n; ++i){
int t = dp[0]+dp[1];
dp[0] = dp[1];
dp[1] = t;
}
return dp[1];
}
};
边栏推荐
- 深度学习21天——卷积神经网络(CNN):实现mnist手写数字识别(第1天)
- C Expert Programming Chapter 4 The Shocking Fact: Arrays and Pointers Are Not the Same 4.5 Other Differences Between Arrays and Pointers
- C专家编程 第5章 对链接的思考 5.3 函数库链接的5个特殊秘密
- Uni-app 小程序 App 的广告变现之路:全屏视频广告
- 高性能高可靠性高扩展性分布式防火墙架构
- 基于gRPC编写golang简单C2远控
- 商城App开发都有哪些功能呢
- 3面头条,花7天整理了面试题和学习笔记,已正式入职半个月
- el-Select 选择器 底部固定
- 【21天学习挑战赛】直接插入排序
猜你喜欢

附加:对于“与数据表对应的实体类“,【面对MongoDB时,使用的@Id等注解】和【以前面对MySQL时,使用的@Id等注解】,是不同的;

如何将 DevSecOps 引入企业?

leetcode 12. Integer to Roman numeral

Shocked, 99.9% of the students didn't really understand the immutability of strings

Performance testing with Loadrunner

ADC噪声全面分析 -03- 利用噪声分析进行实际设计

SLSA 框架与软件供应链安全防护

Explain detailed explanation and practice

8. Haproxy builds a web cluster

深度学习环境配置
随机推荐
【C语言进阶】程序环境和预处理
day13--postman interface test
The difference between px, em, and rem
The idea setting recognizes the .sql file type and other file types
C Expert Programming Chapter 5 Thinking about Linking 5.2 Advantages of Dynamic Linking
烧录场景下开发如何进行源代码保密工作
Cache pool of unity framework
What are the functions of mall App development?
7-2 LVS+DR Overview and Deployment
[SemiDrive source code analysis] [MailBox inter-core communication] 47 - Analysis of RPMSG_IPCC_RPC mode limit size of single transmission and limit bandwidth test
[C language advanced] program environment and preprocessing
Interesting Kotlin 0x0E: DeepRecursiveFunction
Large chain best freight d audit with what software?What are the functions?
震惊,99.9% 的同学没有真正理解字符串的不可变性
3000 words, is take you understand machine learning!
读者让我总结一波 redis 面试题,现在肝出来了
Typora 使用保姆级教程 | 看这一篇就够了 | 历史版本已被禁用
OpenGL绘制一个圆锥
C专家编程 第5章 对链接的思考 5.1 函数库、链接和载入
The 2022 PMP exam has been delayed, should we be happy or worried?