爬楼梯
假设你正在爬楼梯。需要 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 阶
我的思路
思路一
对于第n
阶台阶有多少种爬法这个问题,我们只需要知道n-1
阶和n-2
阶有多少种爬法就可以了(第n
阶台阶,无非是通过n-1
或n-2
阶台阶爬上去的)。
class Solution { public int climbStairs(int n) { if(n==1){ return 1; } if(n == 2 ){ return 2; } return climbStairs(n-2)+climbStairs(n-1); } }
但直接调用会上述的方法出现超时问题。原因是因为算法中存在了大量的重复运算,例如对于求解n=4
,我们实际上对n=2
的子问题重复计算。以此类推,当数值越大,我们重复元素个数就会越多。我们可以通过记忆化搜索的方式来优化这个问题。
class Solution { public static Map<Integer,Integer> map = new HashMap<>(); static { map.put(1,1); map.put(2,2); } public static int climbStairs(int n) { if(map.containsKey(n)){ return map.get(n); } int result = climbStairs(n-2)+climbStairs(n-1); map.put(n,result); return result; } }
答案思路
思路一
延续我之前的思路。代码其实最后可以写成:
这个问题是斐波那契数列的变形。
代码里可以直接这样写
其中result
为F(n)
,temp2
为F(n-1)
,temp2
为F(n-2)
class Solution { public int climbStairs(int n) { if (n < 0) { return -1; } if (n <= 2) { return n; } int temp1 = 1; int temp2 = 2; int result = 0; for (int i = 3; i <= n; i++) { result = temp1 + temp2; temp1 = temp2; temp2 = result; } return result; } }