剑指offer:9.变态跳台阶

https://github.com/PhillipHuang2017/SwordOffer

9.变态跳台阶

题目描述

  • 一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。

解题思路

  • 和简单版跳台阶不同的是,现在一次可以跳1~n级,因此最终跳到第n级台阶时,最后一跳就有n种可能,分别是从第0级,第1级…第n-1级跳上来,得出:

f ( n ) = f ( n 1 ) + f ( n 2 ) + . . . + f ( 1 ) + 1 = 2 f ( n 1 ) = 2 2 f ( n 2 ) . . . = 2 n x f ( x ) = 2 n 1 , w h e n   n > 1 b e c a u s e f ( 1 ) = 1 s o f ( n ) = 2 n 1 , w h e n   n > 0 \begin{aligned} f(n)&= f(n-1) + f(n-2) + ... + f(1) + 1 \\ &= 2*f(n-1) \\ &=2*2*f(n-2) \\ &... \\ &=2^{n-x}*f(x) \\ &=2^{n-1},\quad when\ n > 1 \\ \\ because\quad &f(1) = 1 \\ so\quad &f(n) = 2^{n-1},\quad when\ n > 0 \\ \end{aligned}

  • f(n) = 2^(n-1)
  • 最后加的那个1表示从第0级直接跳上去,把最后那个1当成f(0)也行,只不过在实际问题中无实际意义。
  • 数学归纳法也能找到规律,只不过可能比较慢,不容易想到。

代码

  • 正常操作
class Solution {
public:
    int jumpFloorII(int number) {
        if(number < 0){
            throw "number must > 0";
        }
        int result=1;
        while(--number){
            result *= 2;
        }
        return result;
    }
};
  • 骚操作(左移实现2的次方,速度更快)

左移一次就相当于乘了一个2,计算机进行位运算会更快

class Solution {
public:
    int jumpFloorII(int number) {
        int a=1; 
        return a<<(number-1);
    }
};

https://github.com/PhillipHuang2017/SwordOffer

发布了19 篇原创文章 · 获赞 10 · 访问量 4578

猜你喜欢

转载自blog.csdn.net/Dragon_Prince/article/details/104234342