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),直接用递归超时,改为非递归
代码:
int climbStairs(int n) {
if(n<=0)
return 0;
int *res=new int[n+1];
memset(res,0,sizeof(int)*(n+1));
res[1]=1;
res[2]=2;
int i=3;
while(i < n+1)
{
res[i]=res[i-1]+res[i-2];
++i;
}
return res[n];
}