博客
关于我
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/

    你可能感兴趣的文章
    object detection错误Message type "object_detection.protos.SsdFeatureExtractor" has no field named "bat
    查看>>
    object detection错误之Could not create cudnn handle: CUDNN_STATUS_INTERNAL_ERROR
    查看>>
    object detection错误之no module named nets
    查看>>
    Object of type 'ndarray' is not JSON serializable
    查看>>
    Object Oriented Programming in JavaScript
    查看>>
    object references an unsaved transient instance - save the transient instance before flushing
    查看>>
    Object 类的常见方法有哪些?
    查看>>
    Object-c动态特性
    查看>>
    Object.assign用法
    查看>>
    Object.create
    查看>>
    Object.defineProperty详解
    查看>>
    Object.keys()的详解和用法
    查看>>
    objectForKey与valueForKey在NSDictionary中的差异
    查看>>
    Objective - C 小谈:消息机制的原理与使用
    查看>>
    OBJECTIVE C (XCODE) 绘图功能简介(转载)
    查看>>
    Objective-C ---JSON 解析 和 KVC
    查看>>
    Objective-C 编码规范
    查看>>
    Objective-Cfor循环实现Factorial阶乘算法 (附完整源码)
    查看>>
    Objective-C——判断对象等同性
    查看>>
    objective-c中的内存管理
    查看>>