假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
注意:给定 n 是一个正整数。
1. 暴力法
一开始暴力法我也没想到,其实还是比较容易想到的,递归
//这样的话大概率超时,所以可以用记忆化
public class Solution {
public int climbStairs(int n) {
return climb_Stairs(0, n);
}
public int climb_Stairs(int i, int n) {
if (i > n) {
return 0;
}
if (i == n) {
return 1;
}
return climb_Stairs(i + 1, n) + climb_Stairs(i + 2, n);
}
}
作者:LeetCode
链接:https://leetcode-cn.com/problems/two-sum/solution/pa-lou-ti-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
public class Solution {
public int climbStairs(int n) {
//数组实现记忆化
int memo[] = new int[n + 1];
return climb_Stairs(0, n, memo);
}
public int climb_Stairs(int i, int n, int memo[]) {
if (i > n) {
return 0;
}
if (i == n) {
return 1;
}
if (memo[i] > 0) {
return memo[i];
}
memo[i] = climb_Stairs(i + 1, n, memo) + climb_Stairs(i + 2, n, memo);
return memo[i];
}
}
作者:LeetCode
链接:https://leetcode-cn.com/problems/two-sum/solution/pa-lou-ti-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
//动态规划,实现思路就是当前的位置只能是前一次的结果,两种可能
Javapublic class Solution {
public int climbStairs(int n) {
if (n == 1) {
return 1;
}
int[] dp = new int[n + 1];
dp[1] = 1;
dp[2] = 2;
for (int i = 3; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
}
作者:LeetCode
链接:https://leetcode-cn.com/problems/two-sum/solution/pa-lou-ti-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
//矩阵快速幂
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;
}
}
作者:LeetCode
链接:https://leetcode-cn.com/problems/two-sum/solution/pa-lou-ti-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
这里简单的说一下矩阵快速幂的实现:找到f(n)与f(n-1),根据方程组的行列,与系数矩阵的乘积得到结果矩阵
题解给出的最后一种解法是直接求出来斐波那契的表达式,,但是数值过大貌似会有误差pow()的时间复杂度是logn
这篇博客讨论了如何解决力扣上的爬楼梯问题,提供了包括暴力递归、矩阵快速幂在内的多种解法,并提到了斐波那契数列在解题中的应用,以及对于数值计算可能存在的误差问题。
424

被折叠的 条评论
为什么被折叠?



