1.题目
剑指 Offer 10- II. 青蛙跳台阶问题
一只青蛙一次可以跳上1级台阶,也可以跳上2级台阶。求该青蛙跳上一个 n 级的台阶总共有多少种跳法。
答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。
示例 1:
输入:n = 2
输出:2
示例 2:
输入:n = 7
输出:21
示例 3:
输入:n = 0
输出:1
提示:
0 <= n <= 100
2.自我思路及实现
跳到n阶可以从n-1跳一阶,也可以从n-2跳两阶,
1.自顶向下递归,发现超过时间限制,检查递归树,发现出现重复计算
时间:N, 需要计算每个节点
空间N:栈深度为N
class Solution {
public int numWays(int n) {
if(n == 0 || n == 1)
return 1;
int res = numWays(n - 1) + numWays(n - 2);
return ( res >= 1000000007) ? res % 1000000007 : res;
}
}
2. 带DP表的动态规划
时间 N:每个台阶都要算一遍
空间N:表长度为N
3.自底向上动态规划
时间N: 每个台阶算一遍
空间1:引入3个变量
class Solution {
public int numWays(int n) {
if(n == 0 || n == 1)
return 1;
int i = 1;
int j = 1;
int count = 2;
while(count <= n)
{
int res = (i + j) % 1000000007;
i = j;
j = res;
count++;
}
return j;
}
}
3.总结思路及实现
如上
4.矩阵快速幂
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-Solution
链接:https://leetcode-cn.com/problems/climbing-stairs/solution/pa-lou-ti-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
5.通项公式
public class Solution {
public int climbStairs(int n) {
double sqrt5 = Math.sqrt(5);
double fibn = Math.pow((1 + sqrt5) / 2, n + 1) - Math.pow((1 - sqrt5) / 2, n + 1);
return (int)(fibn / sqrt5);
}
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/climbing-stairs/solution/pa-lou-ti-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
4.相关知识
这里形成的数列正好是斐波那契数列,答案要求的 f(n)f(n) 即是斐波那契数列的第 nn 项(下标从 00 开始)。我们来总结一下斐波那契数列第 n 项的求解方法:
- n 比较小的时候,可以直接使用过递归法求解,不做任何记忆化操作,时间复杂度是 O(2^n)O(2n ),存在很多冗余计算。
- 一般情况下,我们使用「记忆化搜索」或者「迭代」的方法,实现这个转移方程,时间复杂度和空间复杂度都可以做到 O(n)O(n)。
- 为了优化空间复杂度,我们可以不用保存 f(x - 2)f(x−2) 之前的项,我们只用三个变量来维护 f(x)f(x)、f(x - 1)f(x−1) 和 f(x - 2)f(x−2),你可以理解成是把「滚动数组思想」应用在了动态规划中,也可以理解成是一种递推,这样把空间复杂度优化到了 O(1)O(1)。
- 随着 nn 的不断增大 O(n)O(n) 可能已经不能满足我们的需要了,我们可以用「矩阵快速幂」的方法把算法加速到 O(\log n)O(logn)。
- 我们也可以把 nn 代入斐波那契数列的通项公式计算结果,但是如果我们用浮点数计算来实现,可能会产生精度误差。