LeetCode 70. Climbing stairs [Python]

problem

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?

Example 1:

Input: 2
Output: 2
Explanation: There are two ways to climb to the top of the building. (1st order + 1st order), (2nd order)

Example 2:

Input: 3
Output: 3
Explanation: There are three ways to climb to the top of the building. (1st order + 1st order + 1st order), (1st order + 2nd order), (2nd order + 1st order)

Ideas

Use the Fibonacci sequence to solve.

(1) First, we must list two exceptional stairs, n=1, and n=2.
(2) When n≥3, the method of climbing stairs for the nth ladder consists of two parts. The first part is at n- Climb one step on the ladder of 1 and climb two steps on the ladder of n-2 in the second part. So dp[n] = dp[n-1] + dp[n-2].

Code

class classname(object):
    def __init__(self):
        pass

    def climbStairs(self, n):
        if n == 1:
            return 1
        if n == 2:
            return 2
        first = 1; second = 2
        for i in range(n-2):
            temp = second
            second = first + second
            first = temp
        return second

if __name__ == '__main__':
    s = classname()
    r = s.climbStairs(35)
    print(r)
related information

Learning link: https://wenku.baidu.com/view/d680efcacd22bcd126fff705cc17552707225efe.htmls

Guess you like

Origin blog.csdn.net/qq_41709378/article/details/106744615