当前位置:网站首页>力扣: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]
边栏推荐
- [SemiDrive source code analysis] [MailBox inter-core communication] 47 - Analysis of RPMSG_IPCC_RPC mode limit size of single transmission and limit bandwidth test
- Large chain best freight d audit with what software?What are the functions?
- 某母婴小程序加密参数解密
- Cache pool of unity framework
- See how DevExpress enriches chart styles and how it empowers fund companies to innovate their business
- centos 安装postgresql13 指定版本
- As soon as flink cdc is started, the CPU of the source Oracle server soars to more than 80%. What is the reason?
- Do you think border-radius is just rounded corners?【Various angles】
- How to dynamically add script dependent scripts
- Towards Real-Time Multi-Object Tracking(JDE)
猜你喜欢
随机推荐
附加:对于“与数据表对应的实体类“,【面对MongoDB时,使用的@Id等注解】和【以前面对MySQL时,使用的@Id等注解】,是不同的;
Get the selected content of the radio box
C专家编程 第4章 令人震惊的事实:数组和指针并不相同 4.5 数组和指针的其他区别
字节最爱问的智力题,你会几道?
[One step in place] Jenkins installation, deployment, startup (complete tutorial)
Will the 2023 PMP exam use the new version of the textbook?Reply is here!
Interesting Kotlin 0x0E: DeepRecursiveFunction
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
渗透测试(PenTest)基础指南
你以为border-radius只是圆角吗?【各种角度】
Large chain best freight d audit with what software?What are the functions?
docker安装mysql与宿主机相差8小时的问题。
编程大杂烩(四)
OpenGL绘制一个圆锥
go module的介绍与应用
注意!软件供应链安全挑战持续升级
深度学习21天——准备(环境配置)
腾讯136道高级岗面试题:多线程+算法+Redis+JVM
ADC噪声全面分析 -03- 利用噪声分析进行实际设计
Explain detailed explanation and practice