LeetCode: 70. Climbing stairs-simple

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+ 12.  2
示例2:
输入: 3
输出: 3
解释: 有三种方法可以爬到楼顶。
1.  1+ 1+ 12.  1+ 23.  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:
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_51771374/article/details/111598501