https://github.com/PhillipHuang2017/SwordOffer
9.变态跳台阶
题目描述
- 一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
解题思路
- 和简单版跳台阶不同的是,现在一次可以跳1~n级,因此最终跳到第n级台阶时,最后一跳就有n种可能,分别是从第0级,第1级…第n-1级跳上来,得出:
- 即
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);
}
};