Loading

Climbing Stairs

You are climbing a staircase. It takes n steps to reach the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Example 1:

Input: n = 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps

Example 2:

Input: n = 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

Solution:

class Solution:
    # 通过列举可知,1阶有1种方法,2阶有2种方法,3阶有3种方法,
    # 4阶有5种方法,其符合斐波那契数列,n阶=n-1阶+n-2阶,
    # 于是可用列表s[n]记入n阶有的方法数,并通过s.append()进行记入。
    def climbStairs(self, n: int) -> int:
        s=[1,2]
        if n<=2: # 若为一步就数组第一个值,若为两步就第二个值
            return s[n-1]
        while len(s)<n:
            s.append(s[-1]+s[-2])
        return s[-1]
posted @ 2023-06-19 11:59  Artwalker  阅读(6)  评论(0编辑  收藏  举报
Live2D