leetcode 70. Climbing Stairs

252 阅读1分钟
  1. Climbing Stairs Easy

4651

150

Add to List

Share You are climbing a stair case. It takes n steps to reach to 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: 2 Output: 2 Explanation: There are two ways to climb to the top.

  1. 1 step + 1 step
  2. 2 steps Example 2:

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

思路:动态规划

1.问题拆解,找到问题之间的具体联系 到达n阶楼梯需要的步数f(n),跟f(n-1),f(n-2)有关,f(n-1)又跟f(n-2),f(n-3)有关

2.状态定义 f(n)就是f(n-1)加一级阶梯的所有可能 + f(n-2)加两级阶梯的所有可能

3.递推方程推导 f(n) = f(n-1)+f(n-2)

4.实现 f(0)=0 f(1)=1 f(2)=2 后面的递归就行

代码:python3

class Solution:
    def climbStairs(self, n):
        if n is 1:
            return 1
        if n is 2:
            return 2
        dp=[0]*(n+1)
        dp[0]=0
        dp[1]=1
        dp[2]=2
        for i in range(3,n+1):
            dp[i]=dp[i-1]+dp[i-2]
        return dp[n]
if __name__ == '__main__':
    print(Solution().climbStairs(10))

参考:套路 mp.weixin.qq.com/s?__biz=MzU…