【LeetCode】#70. 爬楼梯

假设你正在爬楼梯。需要 n 阶你才能到达楼顶。

每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?

注意:给定 n 是一个正整数。

示例 1:

输入: 2
输出: 2
解释: 有两种方法可以爬到楼顶。
1. 1 阶 + 1 阶
2. 2 阶


示例 2:

输入: 3
输出: 3
解释: 有三种方法可以爬到楼顶。
1. 1 阶 + 1 阶 + 1 阶
2. 1 阶 + 2 阶
3. 2 阶 + 1 阶

 

思路:写出前几阶的结果,并找其规律可发现f(x)=f(x-1)+f(x-2),由此可以使用动态规划解决此题目。

方法一:动态规划
class Solution {
    public int climbStairs(int n) {
        if(n==1)return 1;
        if(n==2)return 2;
        int i1=1,i2=2;
        for(int i=3;i<=n;i++){
            int temp=i1+i2;
            i1=i2;
            i2=temp;
        }
        return i2;
    }
}
方法二:矩阵快速幂
爬楼梯 - 爬楼梯 - 力扣(LeetCode) (leetcode-cn.com)
public class Solution {
    public int climbStairs(int n) {
        int[][] q = {{1, 1}, {1, 0}};
        int[][] res = pow(q, n);
        return res[0][0];
    }

    public int[][] pow(int[][] a, int n) {
        int[][] ret = {{1, 0}, {0, 1}};
        while (n > 0) {
            if ((n & 1) == 1) {
                ret = multiply(ret, a);
            }
            n >>= 1;
            a = multiply(a, a);
        }
        return ret;
    }

    public int[][] multiply(int[][] a, int[][] b) {
        int[][] c = new int[2][2];
        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 2; j++) {
                c[i][j] = a[i][0] * b[0][j] + a[i][1] * b[1][j];
            }
        }
        return c;
    }
}

知识点:

总结:

若是找规律的题目应积极想到动态规划。

posted @ 2021-09-15 17:28  Canyooo  阅读(38)  评论(0)    收藏  举报