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?
Note: Given n will be a positive integer.
总结就是,有n级台阶,每次走一级或者走2级一共有多少种类走法。
动态规划,走一级就是一级以前的走法的种类数,走两级就是两级以前的走法的种类数,两边一加就是这一级台阶的种类数。
代码:
class Solution {
public:
int fib(int n){
if(n == 0) return 0;
else if(n == 1) return 1;
else if(n == 2) return 2;
else return fib(n-1) + fib(n-2);
}
int climbStairs(int n) {
return fib(n);
}
};
但是出问题了,
Time Limit Exceeded
用递归太浪费时间了。那么改成迭代吧,
代码:
class Solution {
public:
int fib(int n){
if(n == 0) return 0;
else if(n == 1) return 1;
else if(n == 2) return 2;
else {
int lastone = 2;
int lasttwo = 1;
int all;
for(int i = 3; i <= n; ++i){
all = lastone + lasttwo;
lasttwo = lastone;
lastone = all;
}
return all;
}
}
int climbStairs(int n) {
return fib(n);
}
};