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?
?
分析:考慮走第n步時的情況,可以從第n-1個臺階走一步,也可以從第n-2個臺階走兩步。即f(n) = f(n-1) + f(n-2),同時f(1) = 1, f(2) = 2.
?
1. 使用遞歸,結果超時了。


class Solution { public:int climbStairs(int n) {if(n == 1) return 1;if(n == 2) return 2;else return(climbStairs(n-1) + climbStairs(n-2));} };
2. 和斐波那契亞數列差不多,于是用了for循環來代替,2ms。
1 class Solution { 2 public: 3 int climbStairs(int n) { 4 if(n <= 2) return n; 5 6 int *result = new int[n]; 7 result[0] = 1; 8 result[1] = 2; 9 for(int i = 2; i < n; i++) 10 result[i] = result[i-1] + result[i-2]; 11 12 return result[n-1]; 13 } 14 };