码迷,mamicode.com
首页 > 其他好文 > 详细

70. Climbing Stairs

时间:2016-08-09 00:00:12      阅读:339      评论:0      收藏:0      [点我收藏+]

标签:

1. 问题描述

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?
Tags:Dynamic Programming

2. 解题思路

  简单分析之:

  • f(1) = 1;
  • f(2) = 2;
  • f(3) = f(2) + f(1) = 3
  • ...
  • f(n) = f(n-1) + f(n-2)
  • 即,Fibonacci数列

3. 代码

 

class Solution 
{
public:
    //递归方法:在LeetCode测试,发现超时
    int climbStairs_recur(int n)
    {
        if (1 == n)
        {
            return  1;
        }
        else if (2 == n)
        {
            return 2;
        }
        else
        {
            return climbStairs_recur(n-2) + climbStairs_recur(n-1);
        }
    }
    //循环方法:利用了上一次的计算结果,速度快
    int climbStairs_loop(int n)
    {
        if (1 == n)
        {
            return  1;
        }
        else if (2 == n)
        {
            return 2;
        }

        int cur = 2;
        int last = 1;
        for (int i=3; i<=n; i++)
        {
            int t =  last + cur;
            last = cur;
            cur = t;
        }
        return cur;        
    }
};

 

4. 反思

70. Climbing Stairs

标签:

原文地址:http://www.cnblogs.com/whl2012/p/5751269.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!