题目参见: http://oj.leetcode.com/problems/climbing-stairs/
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?
典型的斐波那契数列,递归的代码很简单,可惜TLE。
public int climbStairs(int n) {
if(n<=2) {
return n;
}
return climbStairs(n-1) + climbStairs(n-1);
}
那就写一个递推的吧,只用了2个临时变量,AC了。
public int climbStairs(int n) {
if(n<=2) {
return n;
}
int pre = 1;
int result = 2;
for(int i=3;i<=n;i++) {
result = result + pre;
pre = result - pre;
}
return result;
}