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?
分析:若n=1,1种;n=2,2种;n=3,3种;n=4,5种;n=5,8种......即有n阶楼梯时,爬楼梯的方法数有(n-1阶所含方法数 + n-2阶所含方法数)。记得分配指针内存及释放内存,否则会The Time Limit.
class Solution {
public:
int climbStairs(int n) {
if(n<=3) return n;
int *res = new int[n];
res[0]=1;
res[1]=2;
res[2]=3;
for(int i=3;i<n;i++){
res[i] = res[i-1]+res[i-2];
}
int sum = res[n-1];
delete res;//释放内存
return sum;
}
};