题目
假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
链接:https://leetcode.com/problems/climbing-stairs/
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Note: Given n will be a positive integer.
Example:
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1.1 step + 1 step
2.2 steps
思路及代码
DP
- S[j]:到达第j级可以有的不同方法
- S[j] = S[j-1] + S[j-2]:到达第j级可以从j-1级跨一级或者从j-2级跨两级
- 初始值:S[1] = 1, S[2] = 2
class Solution:
def climbStairs(self, n: int) -> int:
if n == 2:
return 2
if n == 1:
return 1
s1 = 1
s2 = 2
s = 0
for i in range(3, n+1):
s = s1 + s2
s1 = s2
s2 = s
return s
复杂度
T = O(n)O(n)O(n)
S = O(1)O(1)O(1)