当前位置:网站首页>算法-- 爬楼梯(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.这个题一下没有想出来怎么做
看了一下题解才做出来
边栏推荐
- Using stopwatch to count code time
- UCF(2022暑期团队赛一)
- Codeforces Round #804 (Div. 2)
- 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
- GAMES202-WebGL中shader的編譯和連接(了解向)
- Postman test report
- Cve-2019-11043 (PHP Remote Code Execution Vulnerability)
- F12 solve the problem that web pages cannot be copied
- Postman pre script - global variables and environment variables
- Ora-01779: the column corresponding to the non key value saving table cannot be modified
猜你喜欢

Steady, 35K, byte business data analysis post

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

注释、接续、转义等符号

flutter 实现一个有加载动画的按钮(loadingButton)

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

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

【OSPF 和 ISIS 在多路访问网络中对掩码的要求】

RT thread analysis log system RT_ Kprintf analysis

What are the advantages of the industry private network over the public network? What specific requirements can be met?

Microblogging hot search stock selection strategy
随机推荐
Easy to understand I2C protocol
Extension of graph theory
驱动开发——第一个HelloDDK
GAMES202-WebGL中shader的編譯和連接(了解向)
C进阶-数据的存储(上)
idea一键导包
Unity gets the width and height of Sprite
Codeforces Round #804 (Div. 2) Editorial(A-B)
04. 项目博客之日志
Tetris
Cuda11.1 online installation
UCF (2022 summer team competition I)
Imperial cms7.5 imitation "D9 download station" software application download website source code
Simple understanding of interpreters and compilers
C AES encrypts strings
Sorting out the knowledge points of multicast and broadcasting
Qt TCP 分包粘包的解决方法
Application of Flody
Vulhub vulnerability recurrence 71_ Unomi
Solution of QT TCP packet sticking