题目:
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?
这也是一道简单而典型的动态规划,用vt[i]记录爬到第i+1层楼梯的方法数。对于vt[i]有两种可能:最近的一步要么是爬1层楼梯到达的,要么是爬了2层楼梯到达的。所以,状态转移方程:vt[i]=vt[i-1]+vt[i-2];
代码:
class Solution {
public:
int climbStairs(int n) {
if(n<=0)return -1;
if(n==1)return 1;
if(n==2)return 2;
vector <int> vt(n,0);
vt[0]=1;
vt[1]=2;
int i=0;
for(i=2;i<n;i++)
vt[i]=vt[i-1]+vt[i-2];
return vt[n-1];
}
};