题目描述
一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
分析
- 当n=1,只有一种跳法
- 当n=2,有两种跳法
- 否则,青蛙跳到第n级台阶之前,可以从第n-1级和第n-2级跳过去,所以f(n)=f(n-1)+f(n-2),这个问题变成了斐波那契问题
public class Solution {
public int JumpFloor(int target) {
if(target <= 2)return target;
int result = 0;
int pre = 1;
int next = 2;
for(int i=3; i<=target; i++){
result = pre + next;
pre = next;
next = result;
}
return result;
}
}
或更简洁的递归
public class Solution {
public int JumpFloor(int target) {
if(target <= 2)return target;
return JumpFloor(target-1) + JumpFloor(target-2);
}
}
变态跳台阶问题
一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
分析
青蛙跳到第n级台阶之前,可以从起点、第1级、第2级……第n-1级起跳。那么跳法就有f(n) = f(n-1) + f(n-2) + …… + f(1) + 1 = 2 * f(n-1)
所以f(n) = 2^(n-1)
public class Solution {
public int JumpFloorII(int target) {
return 1<<(target-1);
}
}
矩形覆盖问题
我们可以用2*1的小矩形横着或者竖着去覆盖更大的矩形。请问用n个2*1的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?
分析
其实就是小矩形是横着放还是竖着放的问题,横着放+2,竖着放+1,和跳台阶是一样的,最终都可以转化为斐波那契数列问题