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

10 Convolutional Neural Networks for Deep Learning 3
![[C language advanced] program environment and preprocessing](/img/ac/a13dd2cc47136d4938b6fc7fad660c.png)
[C language advanced] program environment and preprocessing

解决错误:npm WARN config global `--global`, `--local` are deprecated

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

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

Mini program + e-commerce, fun new retail

day13--postman接口测试

day13--postman interface test
![[One step in place] Jenkins installation, deployment, startup (complete tutorial)](/img/f2/15fb546eb864d7ff40b5507d5c7aa5.png)
[One step in place] Jenkins installation, deployment, startup (complete tutorial)

System design. Seckill system
随机推荐
word 公式编辑器 键入技巧 | 写数学作业必备速查表
获取单选框选中内容
C Expert Programming Chapter 4 The Shocking Fact: Arrays and pointers are not the same 4.4 Matching declarations to definitions
As soon as flink cdc is started, the CPU of the source Oracle server soars to more than 80%. What is the reason?
The symbol table
Towards Real-Time Multi-Object Tracking(JDE)
Dynamic programming of the division of numbers
C专家编程 第4章 令人震惊的事实:数组和指针并不相同 4.1 数组并非指针
How to open a CITIC Securities online account?is it safe?
SLSA 框架与软件供应链安全防护
The difference between px, em, and rem
【SemiDrive源码分析】【MailBox核间通信】47 - 分析RPMSG_IPCC_RPC 方式 单次传输的极限大小 及 极限带宽测试
符号表
备份工具pg_dump的使用《postgres》
DataTable uses Linq for grouping and summarization, and converts the Linq result set into DataTable
docker安装mysql与宿主机相差8小时的问题。
BFC、IFC、GFC、FFC概念理解、布局规则、形成方法、用处浅析
What is the salary of a software testing student?
[Cocos 3.5.2]开启模型合批
少年成就黑客,需要这些技能