博客
关于我
Leetcode|70. 爬楼梯【笔记】
阅读量:712 次
发布时间:2019-03-21

本文共 1026 字,大约阅读时间需要 3 分钟。

爬楼梯问题解析

爬楼梯问题要求我们计算爬到n阶楼梯的不同方法数,每次可以爬1或2阶台阶。这个问题可以通过斐波那契数列来解决,其解答方法包括递归、动态规划、矩阵快速幂等。

4种常见解法:

  • 递归方法

    递归的思路是用费波那契的性质: f(n) = f(n-1) + f(n-2)
    例子:

    import functools@functools.lru_cache(maxsize=None)def climbStairs(n: int) -> int:    if n == 1:        return 1    if n == 2:        return 2    return climbStairs(n - 1) + climbStairs(n - 2)
  • 动态规划优化

    使用动态规划存储前两步结果,节省空间。
    例子:

    def climbStairs(n: int) -> int:    if n == 1 or n == 2:        return n    a, b, temp = 1, 2, 0    for i in range(3, n + 1):        temp = a + b        a = b        b = temp    return temp
  • 斐波那契公式

    使用矩阵快速幂或公式直接计算。
    例子:

    import mathdef climbStairs(n: int) -> int:    if n < 2:        return 1    sqrt5 = math.sqrt(5)    return int(( (1 + sqrt5) ** (n + 1) - (1 - sqrt5) ** (n + 1) ) / (2 * sqrt5))
  • 斐波那契数列的通项

    借助斐波那契数列的通项计算。
    例子:

    import mathdef climbStairs(n: int) -> int:    if n == 1:        return 1    elif n == 2:        return 2    elif n < 0:        return 0    return _fib(n + 1)
  • 关键点总结:

    • 问题基于斐波那契数列。
    • 递归角度计算,需缓存优化。
    • 动态规划优化空间使用,常数空间。
    • 斐波那契公式适用于大数计算。
    • 动态规划常数空间优化方案较为高效。

    转载地址:http://pgaez.baihongyu.com/

    你可能感兴趣的文章
    NO 157 去掉禅道访问地址中的zentao
    查看>>
    No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
    查看>>
    No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
    查看>>
    No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
    查看>>
    No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
    查看>>
    No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
    查看>>
    No module named 'crispy_forms'等使用pycharm开发
    查看>>
    No module named cv2
    查看>>
    No module named tensorboard.main在安装tensorboardX的时候遇到的问题
    查看>>
    No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
    查看>>
    No new migrations found. Your system is up-to-date.
    查看>>
    No qualifying bean of type XXX found for dependency XXX.
    查看>>
    No resource identifier found for attribute 'srcCompat' in package的解决办法
    查看>>
    no session found for current thread
    查看>>
    No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
    查看>>
    NO.23 ZenTaoPHP目录结构
    查看>>
    NO32 网络层次及OSI7层模型--TCP三次握手四次断开--子网划分
    查看>>
    NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
    查看>>
    Node JS: < 一> 初识Node JS
    查看>>
    Node-RED中使用JSON数据建立web网站
    查看>>