题目:
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?
难度:easy 通过率:38.3%
这道题题意是说爬楼梯有一次爬一格和一次爬两格两种方法,问爬n阶楼梯有多少方案?一开始直接使用递归,每次爬法都等于上一次是爬两格或者上一次爬一次的爬法运用加法原理加起来,代码如下:
class Solution {
public:
int climbStairs(int n) {
if(n == 1 ) return 1;
if(n == 2) return 2;
return climbStairs(n-1) +climbStairs(n-2);
}
};
然而超时了~于是运用动态转移,想法和递归差不多,得代码如下:
时间复杂度:O(n)
class Solution {
public:
int climbStairs(int n) {
if(n == 1 ) return 1;
if(n == 2) return 2;
vector<int> v(n);
v[0] = 1;
v[1] = 2;
for(int i = 2; i < n; i++) {
v[i] = v[i-1] + v[i-2];
}
return v[n-1];
}
};