题目描述:
一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。
求该青蛙跳上一个n级的台阶总共有多少种跳法。
思路:
第一种解法:
1. f(1) = 1;
2. f(2) = 2;
= f(2-1) + f(2-2) = f(1) + f(0) = 2
3. f(3) = f(3-1) + f(3-2) + f(3-3)
= f(2) + f(1) + f(0) = 2 + 1 + 1 = 4
4. f(4) = f(4-1) + f(4-2) + f(4-3) + f(4-4)
...
5. f(n-1) = f(n-1-1)+...+f(3) + f(2) + f(1) + f(0)
6. f(n) = f(n-1) + f(n-2) + ... + f(2) + f(1) + f(0)
= 2f(n-1)
7. 则可以通过递归或者循环的方式完成。
第二种解法:
由于青蛙可以跳跃n步台阶,也就是说想要到达终点台阶,他前面的n-1步都可以
选择跳上去或者不跳上去,而最后一步必须要跳上去。
则每一步都有两种选择,也就是:
可能情况 = 2 * 2 * ... * 2 * 1 = 2^(n-1)
第0步 第1步 .. .第n-1步 最后一步必须跳
代码
public static int jumpFloorInsaneRecursive(int target) {
//解法一的递归解法
if (target < 0)
return -1;
if (target <= 1)
return 1;
int result = 2 * jumpFloorInsaneRecursive(target - 1);
return result;
}
public static int jumpFloorInsaneLoop(int target) {
// 解法一的循环解法
if (target < 0)
return -1;
if (target <= 1)
return 1;
int nMinusOne = 1;
int result = 0;
// 2循环1次, n循环n-1次
for (int i = 0; i < target - 1; i++) {
result = 2 * nMinusOne;
nMinusOne = result;
}
return result;
}
public static int jumpFloorII(int target) {
// 解法二
if (target < 0)
return -1;
if (target == 0)
return 1;
else
return (int)Math.pow(2, target-1);
}