Topic:
70. Climbing stairs
Suppose you are climbing stairs. It takes n steps to reach the top of the building.
You can climb 1 or 2 steps each time. How many different ways do you have to climb to the top of a building?
Note: Given n is a positive integer.
示例1:
输入: 2
输出: 2
解释: 有两种方法可以爬到楼顶。
1. 1 阶 + 1 阶
2. 2 阶
示例2:
输入: 3
输出: 3
解释: 有三种方法可以爬到楼顶。
1. 1 阶 + 1 阶 + 1 阶
2. 1 阶 + 2 阶
3. 2 阶 + 1 阶
Problem-solving idea:
The method to climb to the nth order is the sum of the methods to climb to the n-1 order and the n-2 order. Because after climbing to step n-1, you can reach step n by climbing another step. After climbing to step n-2, you can climb 2 steps at a time to reach n, or you can climb two 1 steps to n. Therefore, it is only necessary to initialize how many methods there are to climb to step 1 and how to climb to step 2, and then the method to climb to step n can be derived.
Code:
class Solution:
def climbStairs(self, n: int) -> int:
first = 1
second = 2
num = 0
for i in range(2, n):
num = first + second
first = second
second = num
return max(n, num)
operation result: