• 动态规划之爬楼梯问题


    爬楼梯问题是一个常见的动态规划问题,它可以通过不同的方法来解决。以下是一些示例,以便您更好地理解这个问题:

    示例 1:基础递归

    int climbStairs(int n) {
        if (n <= 2) return n;
        return climbStairs(n - 1) + climbStairs(n - 2);
    }
    
    • 1
    • 2
    • 3
    • 4

    这是一个基本的递归方法,但它效率低下,因为它会重复计算相同的子问题。

    示例 2:带记忆化的递归

    int climbStairs(int n, std::vector<int>& memo) {
        if (n <= 2) return n;
        if (memo[n] != 0) return memo[n];
        memo[n] = climbStairs(n - 1, memo) + climbStairs(n - 2, memo);
        return memo[n];
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    这个示例使用了递归,并且通过一个记忆化数组(memo)来避免重复计算,提高了效率。

    示例 3:迭代方法

    int climbStairs(int n) {
        if (n <= 2) return n;
        int a = 1, b = 2, c;
        for (int i = 3; i <= n; i++) {
            c = a + b;
            a = b;
            b = c;
        }
        return c;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    这个示例使用迭代方法,使用两个变量 ab 来保存前两阶的方法数,然后依次计算后续阶的方法数。

    示例 4:矩阵快速幂

    int climbStairs(int n) {
        if (n <= 2) return n;
        std::vector<std::vector<int>> matrix = {{1, 1}, {1, 0}};
        matrix = matrixPower(matrix, n - 2);
        return 2 * matrix[0][0] + matrix[0][1];
    }
    
    std::vector<std::vector<int>> matrixPower(std::vector<std::vector<int>> matrix, int n) {
        if (n == 1) return matrix;
        if (n % 2 == 0) {
            std::vector<std::vector<int>> temp = matrixPower(matrix, n / 2);
            return multiply(temp, temp);
        } else {
            std::vector<std::vector<int>> temp = matrixPower(matrix, n / 2);
            return multiply(multiply(temp, temp), matrix);
        }
    }
    
    std::vector<std::vector<int>> multiply(std::vector<std::vector<int>> A, std::vector<std::vector<int>> B) {
        std::vector<std::vector<int>> result(2, std::vector<int>(2, 0));
        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 2; j++) {
                for (int k = 0; k < 2; k++) {
                    result[i][j] += A[i][k] * B[k][j];
                }
            }
        }
        return result;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    这个示例使用矩阵快速幂的方法,通过将问题转化为矩阵乘法来解决。

    这些示例展示了解决爬楼梯问题的不同方法,从基本的递归到更高效的动态规划和矩阵快速幂方法。您可以根据实际需求和性能要求来选择适当的方法。

  • 相关阅读:
    Win11通过注册表或者kernel32.dll的SetUserGeoName等方式设置国家或地区后重启过一会就自动变回原来的值...
    VUE之旅—day3
    gpio模拟串口通信
    10.第十部分 Scrapy框架
    【计算机图形学入门】笔记3:变换Transformation(二维与三维)
    会话技术—cookie&Session
    【编译原理】词法分析
    Spring事件ApplicationEvent源码浅读
    【分类网络】VGG
    智慧农业大数据平台:农业中的“大智慧”
  • 原文地址:https://blog.csdn.net/qq_42244167/article/details/133949252