当前位置:网站首页>力扣70-爬楼梯——动态规划
力扣70-爬楼梯——动态规划
2022-07-17 17:15:00 【张怼怼√】
题目描述
假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶
解题思路
- 首先考虑一层台阶:1种方法:1;
- 两层台阶:2种方法:1+1,2;
- 三层台阶:3种方法:1+1+1,1+2,2+1;
- 四层台阶:5种方法:1111,121,211,112,22;
然后发现存在一个规律:当前 i 层台阶的方法 = i - 1 方法 + i - 2 方法;
- 所以能够写出动态规划状态转移方程dp【i】= dp【i-1】 + dp【i - 2】;
- 所以建立三个变量 p q r 分别代表 i-2 ,i-1,i 的方法数;
- 通过遍历就可以求解出台阶数为 n 时的爬楼梯方法。
输入输出示例

代码
class Solution {
public int climbStairs(int n) {
if(n <= 2) return n;
int p = 1;
int q = 2;
int r = 0;
for(int i = 2; i < n; i++){
r = p + q;
p = q;
q = r;
}
return r;
}
}边栏推荐
- Figure execution engine (II)
- 稳超胜算,历9弥新 | 2022金仓创新产品发布会顺利召开
- Porphyrin encapsulated organometallic frame materials [email protected] | Yunxi focuses on store broadcast solutions to accelerate global layout
- Mycat2 builds MySQL master-slave separation
- Flask源码分析(三):上下文
- Cobalt iron bimetallic organic skeleton cox/mil-100 (FE) | [email protected]
- [C language programming 7] BTB model
- Logical operator 1 (Gretel software - Jiuye training)
- OpenCV:06形态学
猜你喜欢

Azkaban 安装文档
[email protected] )|Shell core"/>Cadmium sulfide supported mil-125 (TI) | streptavidin (SA) - zirconium porphyrin MOF composite (PCN- [email protected] )|Shell core

The leader of the new generation of cloud database -- AWS

About the "bottom reading" mentality, it makes you exhausted 2020-03-15

懒到骨子里了,我在CSDN写文章都懒得自己写了,基于selenium模拟写文章

Detailed explanation of RAID disk array, raid classification, advantages and disadvantages

Audio common terminal anatomy - never make a mistake again

标签球问题

又错了,字节对齐及#pragma pack的使用

Metal organic framework / nitrogen carbide nano sheet (uio-66/hocn) composite | mil-101 loaded Au Pd alloy nanoparticles | chemical reagent MOF customization
随机推荐
Azkaban 安装文档
Minimum exchange times
国产API工具哪家强?原来是它…
35岁以上的测试/开发程序员职业生涯走向,是职场转折点吗?
2022年最新吉林建筑安全员模拟题库及答案
虞美人·寄公度
音频常见端子剖析图---再也不会搞错了
Mysql database tables add fields, delete fields, modify the arrangement of fields and other operations, but not soon
When will the moon appear
Audio common terminal anatomy - never make a mistake again
Differences between get requests and post requests and usage examples
Summary of ultrasonic sensor series articles
通货收缩的市场何时反转?我们该如何操作?2020-03-13
全球金融危机来袭,如何科学理性投资?2020-03-17
最懂你的服装设计师是AI?让用户 “凭心意” 生成数字服装#Adidas OZWORLD
基于STM32设计的云端健康管理系统(采用阿里云物联网平台)
go web
松下A6伺服驱动器外部绝对值光栅尺全闭环参数设置
When will the deflationary market reverse? How should we operate? 2020-03-13
Which domestic API tool is better? It turned out to be it