Leetcode Climbing Stairs python 递归和动态规划

Leetcode 70题. Climbing Stairs
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?

Note: Given n will be a positive integer.

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.
4. 1 step + 1 step + 1 step
5. 1 step + 2 steps
6. 2 steps + 1 step

题目大意: 爬N阶楼梯,只能用1或2组成,有多少种组法。

递归解法:
因为只用1和组成,每多一种解法,其实是前一种解法的基础上加一步,以及前两种解法的基础上加两步。 所以 step[n] = step[n-1] + step[n-2] 是经典的递归问题,兔子问题,斐波那契数列。

代码直接出来:

class Solution:
    def climbStairs(self, n: int) -> int:
        if(n==1): return 1
        if(n==2): return 2
        return self.climbStairs(n-1)+self.climbStairs(n-2)

很遗憾,简单的递归需要的空间太大,超时。

优化:
动态规划:
把问题框在相邻的三个元素中间。即:

class Solution:
    def climbStairs(self, n: int) -> int:
        dp = [0] * n
        for i in range(n):
            if i == 0:
                dp[i] = 1
            elif i == 1:
                dp[i] = 2
            else:
                dp[i] = dp[i - 1] + dp[i - 2]
        return dp[n - 1]

初始化的大小是n,但因为保存了0的位置步数是1,要求n的步数,所以总的是N-1个状态

结束。

发布了20 篇原创文章 · 获赞 1 · 访问量 806

猜你喜欢

转载自blog.csdn.net/weixin_43860294/article/details/104742981
今日推荐