Solution 1: 递归,超时=。=
public class Solution {
public int climbStairs(int n) {
if(n < 1) return 0;
if(1 == n) return 1;
if(2 == n) return 2;
return climbStairs(n - 1) + climbStairs(n - 2);
}
}
Solution 2: 使用动态规划,从前向后计算,减少重复计算次数。过程类似于斐波那契数列,只不过是从1,2开始的
public class Solution {
public int climbStairs(int n) {
if(n < 0) return 0;
if(1 == n) return 1;
if(2 == n) return 2;
int oneStepBack = 2;
int twoStepBack = 1;
int totalWays = 0;
for(int i = 3; i <= n; i++){
totalWays = oneStepBack + twoStepBack;
twoStepBack = oneStepBack;
oneStepBack = totalWays;
}
return totalWays;
}
}