lhl
首页
python
leetcode
产品思想
软件测试
博客 (opens new window)
github (opens new window)
首页
python
leetcode
产品思想
软件测试
博客 (opens new window)
github (opens new window)
  • python

  • leetcode

    • 数组

    • 位运算

    • 动态规划

      • 53.最大子数组和
      • 70 爬楼梯
      • 121.买卖股票的最佳时机
      • 338. 比特位计数
    • 链表

    • 栈

    • 树

  • 软件测试

  • Git

  • linux

  • 产品

  • MySql

  • docker

  • leetcode
  • dp
2023-04-29

70 爬楼梯

https://leetcode.cn/problems/climbing-stairs/ (opens new window) 需要注意的点

  1. 关键是找对关系,f(n) = f(n-1) + f(n-2), f(1) = 1,f(2) = 2
  2. 提供两种类似解法,使用数组和不使用数组
class Solution:
    def climbStairs(self, n: int) -> int:
        if n <= 2:
            return n

        a = 1
        b = 2
        for i in range(2, n):
            a,b = b, a+b
        
        return b
class Solution:
    def climbStairs(self, n: int) -> int:

        # f(1) = 1
        # f(2) = 2

        # f(3) = 1 + 2 = f(1) + f(2)
        # f(4) = f(2) + f(3)
        # 到3层跨一步,到2层跨两步

        stairs = [1,2]
        for i in range(2, n):
            stairs.append(stairs[-1] + stairs[-2])
        
        return stairs[n-1]

done动态规划

53.最大子数组和
121.买卖股票的最佳时机

← 53.最大子数组和 121.买卖股票的最佳时机→

最近更新
01
lhl learn notes
02
filter
06-09
03
decorator
06-09
更多文章>
Theme by Vdoing
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式