题目如下。
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?
谢谢木易先森的点拨,f(n)表示爬n个台阶的方法数,f(n) = f(n-1) + f(n-2);
f(1) = 1;
f(2) =2;
以此迭代即可。
public class Solution {
public int climbStairs(int n) {
int s1 = 1;
int s2 = 2;
int result = 0;
if(n < 1)
return 0;
else if(n < 2)
return 1;
else if(n < 3)
return 2;
else{
for(int i = 0; i < n - 2; i ++){
result = s1 + s2;
s1 = s2;
s2 = result;
}
}
return result;
}
}