当前位置:网站首页>力扣: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]
边栏推荐
- Get the selected content of the radio box
- 【21天学习挑战赛】图像的旋转问题(二维数组)
- 深度学习21天——卷积神经网络(CNN):实现mnist手写数字识别(第1天)
- [One step in place] Jenkins installation, deployment, startup (complete tutorial)
- drools from download to postman request success
- 7-2 LVS+DR Overview and Deployment
- System design. Seckill system
- 震惊,99.9% 的同学没有真正理解字符串的不可变性
- Use Patroni callback script to bind VIP pit
- How to simplify the automation of modern e-procurement?
猜你喜欢
Simple operation of the file system
Teenage Achievement Hackers Need These Skills
数的划分之动态规划
[Evaluation model] Topsis method (pros and cons distance method)
附加:对于“与数据表对应的实体类“,【面对MongoDB时,使用的@Id等注解】和【以前面对MySQL时,使用的@Id等注解】,是不同的;
idea设置识别.sql文件类型以及其他文件类型
Turn: Management is the love of possibility, and managers must have the courage to break into the unknown
编程大杂烩(三)
腾讯136道高级岗面试题:多线程+算法+Redis+JVM
Dynamic programming of the division of numbers
随机推荐
What are the functions of mall App development?
C专家编程 第5章 对链接的思考 5.2 动态链接的优点
2022年PMP考试延迟了,该喜该忧?
字节最爱问的智力题,你会几道?
Get the selected content of the radio box
C专家编程 第4章 令人震惊的事实:数组和指针并不相同 4.4 使声明与定义相匹配
static在不同位置定义变量居然还有不同的含义?
QT 如何识别文件的编码格式
C专家编程 第4章 令人震惊的事实:数组和指针并不相同 4.5 数组和指针的其他区别
Turn: Management is the love of possibility, and managers must have the courage to break into the unknown
2023年PMP考试会用新版教材吗?回复来了!
深度学习21天——准备(环境配置)
触觉智能分享-SSD20X实现升级显示进度条
C专家编程 第4章 令人震惊的事实:数组和指针并不相同 4.3 什么是声明,什么是定义
[Cocos] cc.sys.browserType可能的属性
go module的介绍与应用
一个对象引用的思考
C Expert Programming Chapter 5 Thinking about Linking 5.2 Advantages of Dynamic Linking
【流程图】
【21 Days Learning Challenge】Direct Insertion Sort