当前位置:网站首页>力扣: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]
边栏推荐
- 编程大杂烩(三)
- idea设置识别.sql文件类型以及其他文件类型
- Gartner 权威预测未来4年网络安全的8大发展趋势
- 深度学习21天——准备(环境配置)
- 入坑软件测试的经验与建议
- Turn: Management is the love of possibility, and managers must have the courage to break into the unknown
- C专家编程 第4章 令人震惊的事实:数组和指针并不相同 4.5 数组和指针的其他区别
- 深度学习21天——卷积神经网络(CNN):实现mnist手写数字识别(第1天)
- C Expert Programming Chapter 4 The Shocking Fact: Arrays and Pointers Are Not the Same 4.5 Other Differences Between Arrays and Pointers
- SLSA 框架与软件供应链安全防护
猜你喜欢

使用Loadrunner进行性能测试

ADC噪声全面分析 -03- 利用噪声分析进行实际设计

7-3 LVS+Keepalived Cluster Description and Deployment

System design. Seckill system

3000 words, is take you understand machine learning!

There is an 8 hour difference between the docker installation of mysql and the host.

编程大杂烩(三)

关于yolo7和gpu

企业需要知道的5个 IAM 最佳实践

Dynamic programming of the division of numbers
随机推荐
OpenGL绘制圆
深度学习环境配置
渗透测试(PenTest)基础指南
看DevExpress丰富图表样式,如何为基金公司业务创新赋能
解决错误:npm WARN config global `--global`, `--local` are deprecated
某母婴小程序加密参数解密
【云原生--Kubernetes】Pod资源管理与探针检测
2022年PMP考试延迟了,该喜该忧?
使用Patroni回调脚本绑定VIP的坑
C专家编程 第4章 令人震惊的事实:数组和指针并不相同 4.1 数组并非指针
烧录场景下开发如何进行源代码保密工作
leetcode 12. 整数转罗马数字
DataTable uses Linq for grouping and summarization, and converts the Linq result set into DataTable
idea设置识别.sql文件类型以及其他文件类型
[C language advanced] program environment and preprocessing
附加:对于“与数据表对应的实体类“,【面对MongoDB时,使用的@Id等注解】和【以前面对MySQL时,使用的@Id等注解】,是不同的;
编程大杂烩(四)
What are the functions of mall App development?
Teenage Achievement Hackers Need These Skills
Interesting Kotlin 0x0E: DeepRecursiveFunction