当前位置:网站首页>力扣: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]
边栏推荐
- 想低成本保障软件安全?5大安全任务值得考虑
- 力扣题解8/3
- How to dynamically add script dependent scripts
- OpenGL绘制一个圆锥
- Simple operation of the file system
- 转:管理是对可能性的热爱,管理者要有闯进未知的勇气
- C Expert Programming Chapter 4 The Shocking Fact: Arrays and pointers are not the same 4.4 Matching declarations to definitions
- 入坑软件测试的经验与建议
- 深度学习环境配置
- 使用Patroni回调脚本绑定VIP的坑
猜你喜欢

7-2 LVS+DR Overview and Deployment

The symbol table

在被面试官说了无数次后,终于潜下心来整理了一下JVM的类加载器

share总结
![[Cocos 3.5.2]开启模型合批](/img/d9/9e8f71c9a26c8052b11291fe3ba7ac.png)
[Cocos 3.5.2]开启模型合批

Simple operation of the file system

What is the salary of a software testing student?
![[One step in place] Jenkins installation, deployment, startup (complete tutorial)](/img/f2/15fb546eb864d7ff40b5507d5c7aa5.png)
[One step in place] Jenkins installation, deployment, startup (complete tutorial)

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

深度学习21天——准备(环境配置)
随机推荐
8. Haproxy builds a web cluster
What are the functions of mall App development?
C Expert Programming Chapter 4 The Shocking Fact: Arrays and pointers are not the same 4.1 Arrays are not pointers
See how DevExpress enriches chart styles and how it empowers fund companies to innovate their business
[21 Days Learning Challenge] Image rotation problem (two-dimensional array)
static在不同位置定义变量居然还有不同的含义?
Dynamic programming of the division of numbers
渗透测试(PenTest)基础指南
烧录场景下开发如何进行源代码保密工作
2022软件测试面试题 最新字节跳动50道真题面试题 刷完已拿下15k 附讲解+答疑
商城App开发都有哪些功能呢
Tactile intelligent sharing - SSD20X realizes upgrade display progress bar
Towards Real-Time Multi-Object Tracking(JDE)
mysql index notes
离线采集怎么看sql执行计划
Interesting Kotlin 0x0E: DeepRecursiveFunction
day13--postman interface test
【SemiDrive源码分析】【MailBox核间通信】47 - 分析RPMSG_IPCC_RPC 方式 单次传输的极限大小 及 极限带宽测试
ADC噪声全面分析 -03- 利用噪声分析进行实际设计
使用Patroni回调脚本绑定VIP的坑