zoukankan      html  css  js  c++  java
  • LeetCode 70 Climbing Stairs

    Problem:

    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?

    Summary:

    n级楼梯,每次上1或2阶,求共有多少种不同的上法。

    Analysis:

    这道题实际上为斐波那契数列,有以下几种解法。

    1. 递归

    首先想到的是递归写法,一次上1阶和2阶是两种不同方法,所以上n级楼梯:

    1. 若最后一步上了1阶,则共有climbStairs(n - 1)种方法。
    2. 若最后一步上了2阶,则共有climbStairs(n - 2)种方法。

    对于每一步,都有以上两种不同考虑。

    但递归写法效率太低,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 - 2) + climbStairs(n - 1);
    7     }
    8 };

    2. 思路同上一种方法,改用了动态规划,节省了时间。

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

     3. 下面两种方法参考 http://blog.csdn.net/kenden23/article/details/17377869 在动态规划的基础上节省空间。

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

    或者不开数组,直接用三个变量解决问题

     1 class Solution {
     2 public:
     3     int climbStairs(int n) {
     4         if (n <= 2) return n;
     5         int a = 1, b = 1, c = 2;
     6         
     7         for (int i = 3; i < n + 1; i++) {
     8             a = b;
     9             b = c;
    10             c = a + b;
    11         }
    12         
    13         return c;
    14     }
    15 };
  • 相关阅读:
    植物园偶遇一直喵
    植物园偶遇一直喵
    美食篇
    美食篇
    端午节路过南站
    端午节路过南站
    黄山云海
    黄山云海
    Android (1)
    树和树算法(1)
  • 原文地址:https://www.cnblogs.com/VickyWang/p/6032264.html
Copyright © 2011-2022 走看看