当前位置:网站首页>力扣:70. 爬楼梯
力扣:70. 爬楼梯
2022-08-04 05:14:00 【empty__barrel】
力扣:70. 爬楼梯
题目:
假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
普通代码:
class Solution {
public:
int climbStairs(int n) {
if (n <= 1) return n; // 因为下面直接对dp[2]操作了,防止空指针
vector<int> dp(n + 1);
dp[1] = 1;
dp[2] = 2;
for (int i = 3; i <= n; i++) {
// 注意i是从3开始的
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
};
代码:其实只需要维护两个数值即可
class Solution {
public:
int climbStairs(int n) {
if(n<=2) return n;
int dp[2];
dp[0] = 1;
dp[1] = 2;
for(int i = 2; i <= n-1; ++i) {
int s = dp[0]+dp[1];
dp[0] = dp[1];
dp[1] = s;
}
return dp[1];
}
};
//dp[n] = dp[n-2]+dp[n-1]
边栏推荐
- OpenSSF 安全计划:SBOM 将驱动软件供应链安全
- 7-3 LVS+Keepalived Cluster Description and Deployment
- 败给“MySQL”的第60天,我重振旗鼓,四面拿下蚂蚁金服offer
- Landing, the IFC, GFC, FFC concept, layout rules, forming method, use is analysed
- System design. Seckill system
- About yolo7 and gpu
- 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
- drools from download to postman request success
- Mini program + e-commerce, fun new retail
- day13--postman interface test
猜你喜欢
【云原生--Kubernetes】Pod资源管理与探针检测
【C语言进阶】程序环境和预处理
企业需要知道的5个 IAM 最佳实践
idea设置识别.sql文件类型以及其他文件类型
[One step in place] Jenkins installation, deployment, startup (complete tutorial)
数的划分之动态规划
The idea setting recognizes the .sql file type and other file types
Mini program + e-commerce, fun new retail
在被面试官说了无数次后,终于潜下心来整理了一下JVM的类加载器
如何将 DevSecOps 引入企业?
随机推荐
少年成就黑客,需要这些技能
【一步到位】Jenkins的安装、部署、启动(完整教程)
【21 Days Learning Challenge】Direct Insertion Sort
C专家编程 第4章 令人震惊的事实:数组和指针并不相同 4.2 我的代码为什么无法运行
redis中常见的面试题
C Expert Programming Chapter 4 The Shocking Fact: Arrays and Pointers Are Not the Same 4.5 Other Differences Between Arrays and Pointers
如何打造一篇优秀的简历
获取单选框选中内容
结构体函数练习
8款最佳实践,保护你的 IaC 安全!
使用Loadrunner进行性能测试
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
C Expert Programming Chapter 5 Thinking about Linking 5.3 5 Special Secrets of Library Linking
What are the functions of mall App development?
文献管理工具 | Zotero
System design. Seckill system
Towards Real-Time Multi-Object Tracking (JDE)
在被面试官说了无数次后,终于潜下心来整理了一下JVM的类加载器
数的划分之动态规划
一个对象引用的思考