题目:
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?
思路:这题和前面Unique Paths的题比较类似,也可以用动态规划来做。
定义一个数组DP[n]。
DP[i]表示到第i阶不同的方法。
则满足如下递推关系:
DP[i]=DP[i-1]+DP[i-2] ,i>1
DP[i]=DP[i-1]+1 ,i=1
DP[i]=1 ,i=0
时间复杂度:O(n)
实现如下:
class Solution {
public:
int climbStairs(int n) {
vector<int> DP(n, 0);
if (n <=2) return n;
for (int i = 0; i < n; ++i)
{
if (i < 2) DP[i] = i + 1;
else DP[i] = DP[i - 1] + DP[i - 2];
}
return DP[n - 1];
}
};