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)=f(n-1)+f(n-2)(f(1)=1,f(2)=2)直接递推得出答案
这样导致非常多的冗余计算量,简化该模型,一直累加下去并不需要记录先前的所有值,两个值就够了:
public class Solution {
public int climbStairs(int n) {
int c=1,a=2,b=3;
if(n<4)return n;
while(n>3)
{
c=a+b;
a=b;
b =c;
n--;
}
return b;
}
}