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);
}
};