当前位置:网站首页>力扣: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];
}
};
边栏推荐
猜你喜欢

10 Convolutional Neural Networks for Deep Learning 3

【21天学习挑战赛】图像的旋转问题(二维数组)

【评价类模型】Topsis法(优劣解距离法)
![[Cloud Native--Kubernetes] Pod Resource Management and Probe Detection](/img/1a/b3bdf9b62c82b0fc4d913045981d94.png)
[Cloud Native--Kubernetes] Pod Resource Management and Probe Detection

深度学习21天——准备(环境配置)

8. Haproxy builds a web cluster

7-2 LVS+DR Overview and Deployment

Turn: Management is the love of possibility, and managers must have the courage to break into the unknown

Performance testing with Loadrunner

烧录场景下开发如何进行源代码保密工作
随机推荐
C专家编程 第5章 对链接的思考 5.3 函数库链接的5个特殊秘密
OpenSSF 安全计划:SBOM 将驱动软件供应链安全
C专家编程 第5章 对链接的思考 5.4 警惕Interpositioning
使用Patroni回调脚本绑定VIP的坑
[Cocos 3.5.2]开启模型合批
如何打造一篇优秀的简历
应届生软件测试薪资大概多少?
Introduction and application of go module
Cache pool of unity framework
8款最佳实践,保护你的 IaC 安全!
烧录场景下开发如何进行源代码保密工作
The symbol table
Uni-app 小程序 App 的广告变现之路:全屏视频广告
See how DevExpress enriches chart styles and how it empowers fund companies to innovate their business
Mini program + e-commerce, fun new retail
The Road to Ad Monetization for Uni-app Mini Program Apps: Full Screen Video Ads
C Expert Programming Chapter 5 Thinking about Linking 5.3 5 Special Secrets of Library Linking
DataTable uses Linq for grouping and summarization, and converts the Linq result set into DataTable
在被面试官说了无数次后,终于潜下心来整理了一下JVM的类加载器
[SemiDrive source code analysis] [MailBox inter-core communication] 47 - Analysis of RPMSG_IPCC_RPC mode limit size of single transmission and limit bandwidth test