LeetCode 70. Climbing Stairs

只能用1、2相加得到n,求有几种加法。

ver0:递归,意料之中的TLE

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

ver1:略加修改

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

 

其他版本代码,以后再琢磨。

1 class Solution {
2 public:
3     int climbStairs(int n) {
4        int x[3]={1,1,0},k=1;
5        while(++k<=n)    x[k%3] = x[(k-1)%3] + x[(k-2)%3];
6        return x[n%3];
7     }
8 };

 

posted @ 2016-02-13 22:45  co0oder  阅读(126)  评论(0编辑  收藏  举报