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