public class Solution {
public int climbStairs(int n) {
int res = n - 1;
if(n == 0){
return 0;
}
int[] mem = new int[n];
if(n <= 1){
return 1;
}
if(n == 2){
return 2;
}
mem[0] = 1;
mem[1] = 2;
for(int i = 2 ; i <= n - 1 ; i++){
mem[i] = mem[i - 1] + mem[i - 2];
}
return mem[res];
}
}
似乎是leetcode上面最水的一道题了,不过提交之后居然Time limit exceed,每当这个时候我就毫不犹豫去看discuss,才想起学校其实也有教上面这种方法(
The problem here is that you are doing a lot of the work multiple times. For instance, there is no difference between the paths from a given number if you got there by stepping up 1 stair twice or 2 stairs once. The number of ways to get to the top from that stair remains the same, but you are calculating it twice from scratch. Extend that to 4 stairs above your starting point. You could get there using 1-1-1-1, 2-1-1, 1-2-1, 1-1-2, or 2-2. You now need to calculate f(n-4) 4 times.
To speed this up, you can remember the result for a given number of steps, then just use that result the next time you need that number instead of recalculating the entire process. This "remembering" is called memoization, and is required for quite a few of the problems on this site in order to complete them before the time limit.
http://oj.leetcode.com/discuss/2727/climb-stairs-exceed-time-limits-why),当然最开始接触的是原来的这种会超时的方法:
public class Solution {
public int climbStairs(int n) {
if(n <= 0){
return 0;
}
if(n == 1){
return 1;
}
if(n == 2){
return 2;
}
return climbStairs(n - 1) + climbStairs(n - 2);
}
}