一.问题描述
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?
二.我的解题思路
这道题也很简单,一眼看上去很容易想到用递归的算法去做:T(n)=T(n-1)+T(n-2)。不过如果这样写递归式的话,算法复杂度比较高,有很多重复的子问题。那么此时要想到动态规划的算法,从底向上去做。那么就很容易可以写出测试程序如下:
class Solution {
public:
int climbStairs(int n) {
vector<int> tmp(n+1,0);
tmp[0]=1;tmp[1]=1;
if(n<=0) return 0;
if(n<2) return tmp[n];
int cnt=2;
while(cnt<=n){
tmp[cnt]=tmp[cnt-1]+tmp[cnt-2];
cnt++;
}
return tmp[n];
}
};