Tencent 45-stair climbing

Tencent 45-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 at a time. How many different ways can you climb to the top of the building?

Note: The given n is a positive integer.
Example 1:
Input: 2
Output: 2
Explanation: There are two ways to climb to the top of the building.

  1. Tier 1 + Tier 1
  2. Level 2

Example 2:

Input: 3
Output: 3
Explanation: There are three ways to climb to the top of the building.

  1. 1st order + 1st order + 1st order
  2. 1st order + 2nd order
  3. Tier 2 + Tier 1

Conventional recursion, which can also be said to be dp, can
use a list or dictionary to store the previous calculation result. The
current input parameter can use the result of the previous input parameter, which is dp

class Solution:
    def climbStairs(self, n: int) -> int:
        # if n==0 or n==1:return 1
        # else: return self.climbStairs(n-1)+self.climbStairs(n-2)
        #不能写递归,太深,只能写循环
        res={0:1,1:1}
        for i in range(2,n+1):
            res.update({i:res[i-1]+res[i-2]})
        return res[n]
Published 93 original articles · praised 8 · 10,000+ views

Guess you like

Origin blog.csdn.net/zlb872551601/article/details/103652435