70. Climbing Stairs

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. 反思

posted on 2016-08-08 22:39  whl-hl  阅读(117)  评论(0编辑  收藏  举报

导航