Climbing Stairs [LEETCODE]

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?

==============================================================

Fisrt, I tried recursive way.

1 class Solution {
2 public:
3     int climbStairs(int n) {
4         // Recursively
5         if(0 == n) return 0;
6         if(1 == n) return 1;
7         return climbStairs(n - 1) + climbStairs(n - 2);
8     }
9 };

But this solution exceed time limit.

So let's think about it. One step has only 1 way , 2 steps have two ways.

Thus N steps have two ways to reach destination: N-1 steps plus one step; N-2 steps plus two steps.

So S[n] = S[n-1] + S[n-2]

Here' s the code:

 1 class Solution {
 2 public:
 3     int climbStairs(int n) {
 4         // Recursively
 5         if(0 == n) return 0;
 6         if(1 == n) return 1;
 7         int *step = new int[n+1];
 8         step[0] = 0;
 9         step[1] = 1;
10         step[2] = 2;
11         for(int i =3; i <=n ; i++){
12             step[i] = step[i-1] + step[i-2];
13         }
14         return step[n];
15     }
16 };

Remind to allocate n+1 space to store steps from 0 to n.

posted @ 2013-10-14 17:03  昱铭  阅读(305)  评论(0)    收藏  举报