首页 > 其他 > 详细

Climbing Stairs

时间:2015-04-20 22:09:53      阅读:203      评论:0      收藏:0      [点我收藏+]

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

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

Climbing Stairs

原文:http://www.cnblogs.com/amazingzoe/p/4442650.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!