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?
算是简单的DP,如果想不到会感觉没思路。 最懒的方法是递归,不过时间过不了。
class Solution {
public:
int climbStairs(int n) {
if (n <= 2) {
return n;
}
return (climbStairs(n-1) + climbStairs(n-2));
}
};
改成迭代就可以啦,利用前面计算过的结果。
class Solution {
public:
int climbStairs(int n) {
if (n <= 2) {
return n;
}
int sn, sn2 = 1, sn1 = 2;
for (int i = 3; i <= n; ++i) {
sn = sn2 + sn1;
sn2 = sn1;
sn1 = sn;
}
return sn;
}
};
=====================第二次=====================
class Solution {
public:
int climbStairs(int n) {
if (n <= 2) {
return n;
}
int n1 = 1;
int n2 = 2;
int ways = 0;
for (int i = 3; i <= n; ++i) {
ways = n1 + n2;
n1 = n2;
n2 = ways;
}
return ways;
}
};