当前位置:网站首页>算法-- 爬楼梯(Kotlin)
算法-- 爬楼梯(Kotlin)
2022-07-06 05:18:00 【小米科技Android 研发曹新雨】
题目
假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
示例 1:
输入:n = 2
输出:2
解释:有两种方法可以爬到楼顶。
1. 1 阶 + 1 阶
2. 2 阶
示例 2:
输入:n = 3
输出:3
解释:有三种方法可以爬到楼顶。
1 阶 + 1 阶 + 1 阶
1 阶 + 2 阶
2 阶 + 1 阶
提示:
1 <= n <= 45
https://leetcode.cn/problems/climbing-stairs/
解决思路
- 本问题其实常规解法可以分成多个子问题,爬第n阶楼梯的方法数量,等于 2 部分之和
爬上 n-1阶楼梯的方法数量。因为再爬1阶就能到第n阶
爬上 n-2阶楼梯的方法数量,因为再爬2阶就能到第n阶
所以我们得到公式 dp[n] = dp[n-1] + dp[n-2]
同时需要初始化 dp[0]=1 和 dp[1]=1d
时间复杂度:O(n)
2.既然 dp[n] = dp[n-1] + dp[n-2]
那么我们可以用滑动数组去解决
解决方法
fun climbStairs(n: Int): Int {
val intArray = IntArray(n + 1)
intArray[0] = 1
intArray[1] = 1
for (i in 2..n) {
intArray[i] = intArray[i - 1] + intArray[i - 2]
}
return intArray[n]
}
fun climbStairs2(n: Int): Int {
var q = 1
var p = 1
var result = 1
for (i in 2..n) {
result = q + p
q = p
p = result
}
return result
}
总结
1.这个题一下没有想出来怎么做
看了一下题解才做出来
边栏推荐
- 注释、接续、转义等符号
- Talking about the type and function of lens filter
- Yyds dry inventory SSH Remote Connection introduction
- [effective Objective-C] - memory management
- Oracle query table index, unique constraint, field
- MySQL time processing
- Using stopwatch to count code time
- Building intelligent gray-scale data system from 0 to 1: Taking vivo game center as an example
- UCF(暑期团队赛二)
- UCF(2022暑期团队赛一)
猜你喜欢
Nacos TC setup of highly available Seata (02)
Class inheritance in yyds dry inventory C
趋势前沿 | 达摩院语音 AI 最新技术大全
ByteDance program yuan teaches you how to brush algorithm questions: I'm not afraid of the interviewer tearing the code
SQLite add index
Three methods of Oracle two table Association update
RT thread analysis - object container implementation and function
Pointer classic written test questions
Application of Flody
Review of double pointer problems
随机推荐
Hometown 20 years later (primary school exercises)
[noip2009 popularization group] score line delimitation
Qt TCP 分包粘包的解决方法
2022 half year summary
Why does MySQL need two-phase commit
从0到1建设智能灰度数据体系:以vivo游戏中心为例
02. Develop data storage of blog project
Quelques conseils communs sur l'inspecteur de l'unit é, généralement pour les extensions d'éditeur ou d'autres
Knowledge points of circular structure
[leetcode16] the sum of the nearest three numbers (double pointer)
集合详解之 Collection + 面试题
Talking about the type and function of lens filter
Notes, continuation, escape and other symbols
Implementing fuzzy query with dataframe
【LeetCode】18、四数之和
Simple understanding of interpreters and compilers
浅谈镜头滤镜的类型及作用
Upload nestjs configuration files, configure the use of middleware and pipelines
The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
關於Unity Inspector上的一些常用技巧,一般用於編輯器擴展或者其他