假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
注意:给定 n 是一个正整数。
官方解法:https://leetcode-cn.com/problems/climbing-stairs/solution/pa-lou-ti-by-leetcode-solution/
解法一:动态规划(32ms/15MB)
class Solution:
def climbStairs(self, n: int) -> int:
p = 0
q = 0
r = 1
for i in range(n):
p = q
q = r
r = p + q
return r
解法二:矩阵快速幂
struct Matrix {
long long mat[2][2];
};
struct Matrix multiply(struct Matrix a, struct Matrix b) {
struct Matrix c;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
c.mat[i][j] = a.mat[i][0] * b.mat[0][j] + a.mat[i][1] * b.mat[1][j];
}
}
return c;
}
struct Matrix matrixPow(struct Matrix a, int n) {
struct Matrix ret;
ret.mat[0][0] = ret.mat[1][1] = 1;
ret.mat[0][1] = ret.mat[1][0] = 0;
while (n > 0) {
if ((n & 1) == 1) {
ret = multiply(ret, a);
}
n >>= 1;
a = multiply(a, a);
}
return ret;
}
int climbStairs(int n) {
struct Matrix ret;
ret.mat[1][1] = 0;
ret.mat[0][0] = ret.mat[0][1] = ret.mat[1][0] = 1;
struct Matrix res = matrixPow(ret, n);
return res.mat[0][0];
}
解法三:通项公式(24ms/15MB)
class Solution:
def climbStairs(self, n: int) -> int:
sqrt5 = 5 ** 0.5
fibn = ((1 + sqrt5)/2) ** (n + 1) - ((1 - sqrt5)/2) ** (n + 1)
return int(fibn // sqrt5)
总结:
力扣 (LeetCode)链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xn854d/