You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Note: Given n will be a positive integer.
一刷
题解:dynamic programming,且存在递归的表达式a[n] = a[n-1] + a[n-2]
方法一:直接用递归,但会造成超时,可能是数字太大时栈太长。并且比起用数组存起来中间结果不会更节约space。
public class Solution {
public int climbStairs(int n) {
if(n == 1 || n==0) return 1;
if(n<0) return 0;
return climbStairs(n-1) + climbStairs(n-2);
}
}
方法二:用数组存起来中间结果。
public class Solution {
public int climbStairs(int n) {
int[] res = new int[n+1];
res[0] = 1;
res[1] = 1;
for(int i=2; i<=n; i++){
res[i] = res[i-1] + res[i-2];
}
return res[n];
}
}
方法三,用常量存储 res[i-1], res[i-2]; 将space complexity降到O(1)
public class Solution {
public int climbStairs(int n) {
if(n == 1 || n==0) return 1;
if(n<0) return 0;
int oneStep = 1, twoStep = 2;
if(n == 1) return oneStep;
if(n == 2) return twoStep;
int sum = 0;
for(int i=3; i<=n; i++){
sum = oneStep + twoStep;
oneStep = twoStep;
twoStep = sum;
}
return sum;
}
}