70. Climbing Stairs Easy
Description
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
- Example 1:
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
- Example 2:
Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
题意
每次只能爬一层或者两层,求爬到第n层的总方法数
解题思路
这题看到给的示例,推了一下爬到第4层有5种方法,而到第4层是与第3层和地2层有关的,可以联想到斐波那契数列。
每次只能走1或2层,那么要到达第n层,最后一步都有两种方法,从倒数第一层迈一步,或从倒数第二层迈两步。
code
class Solution:
def climbStairs(self, n: int) -> int:
if n <= 1:
return 1
res = []
res.append(1)
res.append(1)
for i in range(2,n+1):
res.append(res[-2] + res[-1])
return res[-1]