当前位置:网站首页>力扣: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];
}
};
边栏推荐
- How to keep the source code confidential in the development under the burning scenario
- Dynamic programming of the division of numbers
- 某母婴小程序加密参数解密
- manipulation of file contents
- 应届生软件测试薪资大概多少?
- C Expert Programming Chapter 4 The Shocking Fact: Arrays and Pointers Are Not the Same 4.3 What is a Declaration and What is a Definition
- Resolved error: npm WARN config global `--global`, `--local` are deprecated
- 烧录场景下开发如何进行源代码保密工作
- Performance testing with Loadrunner
- mysql index notes
猜你喜欢
随机推荐
redis中常见的面试题
《看见新力量》第四期免费下载!走进十五位科技创业者的精彩故事
结构体指针知识要点总结
震惊,99.9% 的同学没有真正理解字符串的不可变性
深度学习21天——准备(环境配置)
C Expert Programming Chapter 4 The Shocking Fact: Arrays and pointers are not the same 4.1 Arrays are not pointers
8. Haproxy builds a web cluster
DataTable使用Linq进行分组汇总,将Linq结果集转化为DataTable
附加:对于“与数据表对应的实体类“,【面对MongoDB时,使用的@Id等注解】和【以前面对MySQL时,使用的@Id等注解】,是不同的;
Towards Real-Time Multi-Object Tracking(JDE)
3000 words, is take you understand machine learning!
OpenGL绘制圆
Interesting Kotlin 0x0E: DeepRecursiveFunction
C专家编程 第4章 令人震惊的事实:数组和指针并不相同 4.2 我的代码为什么无法运行
渗透测试(PenTest)基础指南
腾讯136道高级岗面试题:多线程+算法+Redis+JVM
2022 software test interview questions The latest ByteDance 50 real interview questions, 15k have been won after brushing, with explanation + Q&A
ADC噪声全面分析 -03- 利用噪声分析进行实际设计
Structure function exercise
【21天学习挑战赛】图像的旋转问题(二维数组)