剑指offer面试题10. 青蛙跳台阶

欢迎访问我的剑指offer(第二版)题解目录
对应的Leetcode题目可点击leetcode 70. Climbing Stairs

题目描述

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?
Note: Given n will be a positive integer.
Example 1:

Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps

Example 2:

Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step

算法设计

假设当有n个台阶时的方案数为 F ( n ) F(n) ,那么我们可以发现 F ( 1 ) = 1 F(1)=1 F ( 2 ) = 2 F(2)=2 ,当 n > 2 n>2 时,分两种情况:

  1. 当最后一步只跨了一个台阶时,方案数为 F ( n 1 ) F(n-1)
  2. 当最后一步跨了两个台阶时,方案数为 F ( n 2 ) F(n-2)

因此当 n > 2 n>2 时, F ( n ) = F ( n 1 ) + F ( n 2 ) F(n)=F(n-1)+F(n-2)
这实质上是一个斐波那契数列,只不过这里的第n项是斐波那契数列的第n+1项。

C++代码

递归( O ( 2 n ) O(2^n)

class Solution {
  public:
    int climbStairs(int n) { return n == 1 ? 1 : n == 2 ? 2 : climbStairs(n - 1) + climbStairs(n - 2); }
};

循环( O ( n ) O(n)

class Solution {
  public:
    int climbStairs(int N) {
        if (N <= 2)
            return N == 1 ? 1 : 2;
        int f0 = 1, f1 = 2;
        for (int i = 3; i <= N; ++i) {
            int f = f0 + f1;
            f0 = f1;
            f1 = f;
        }
        return f1;
    }
};

通项公式( O ( 1 ) O(1)

斐波那契数列的通项公式为 F n = 1 5 [ ( 1 + 5 2 ) n ( 1 5 2 ) n ] F_n=\frac 1 {\sqrt5} \cdot [{(\frac {1+\sqrt5} 2)}^n-{(\frac {1-\sqrt5} 2)}^n]

class Solution {
  public:
    int climbStairs(int n) {
        double sqrt5 = sqrt(5.0);
        return int((pow((1 + sqrt5) / 2.0, n+1) - pow((1 - sqrt5) / 2, n+1)) / sqrt5);
    }
};

事实上,由于当n比较大时, ( 1 5 2 ) n {(\frac {1-\sqrt5} 2)}^n 会非常小,我们可以直接舍弃掉这一项,并利用round函数对 1 5 ( 1 + 5 2 ) n \frac 1 {\sqrt5} \cdot {(\frac {1+\sqrt5} 2)}^n 进行四舍五入,再转换回int类型,也可以得到正确结果,即

class Solution {
  public:
    int climbStairs(int n) {
        double sqrt5 = sqrt(5.0);
        return round(pow((1 + sqrt5) / 2.0, n + 1) / sqrt5);
    }
};
发布了528 篇原创文章 · 获赞 1015 · 访问量 37万+

猜你喜欢

转载自blog.csdn.net/richenyunqi/article/details/103648548
今日推荐