一只青蛙一次可以跳上1级台阶,也可以跳上2级。
求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。
题目前提:只有 一次 1阶或者2阶的跳法。
a.如果两种跳法,1阶或者2阶,那么假定第一次跳的是一阶,那么剩下的是n-1个台阶,跳法是f(n-1);
b.假定第一次跳的是2阶,那么剩下的是n-2个台阶,跳法是f(n-2)
c.由a\b假设可以得出总跳法为: f(n) = f(n-1) + f(n-2)
d.然后通过实际的情况可以得出:只有一阶的时候 f(1) = 1 ,只有两阶的时候可以有 f(2) = 2
e.可以发现最终得出的是一个斐波那契数列:
| 1, (n=1)
f(n) = | 2, (n=2)
| f(n-1)+f(n-2) ,(n>2,n为整数)
package arraydemo;
/**
* @author wyl
* @time 2018年8月21日下午8:48:34
*/
public class Solution9 {
public static void main(String[] args) {
System.out.println(JumpFloor(5));
}
public static int JumpFloor(int target) {
if (target<=0) {
return -1;
}else if (target==1) {
return 1;
}else if (target==2) {
return 2;
}else {
return JumpFloor(target-1)+JumpFloor(target-2);
}
}
}
————————————————————————————————————————————————————————
变型题:
一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。
求该青蛙跳上一个n级的台阶总共有多少种跳法。
台阶 跳法
1 1
2 2 [1,1]、[2]
3 4 [1,1,1]、[2,1]、[1,2]、[3] =2*1+2
4 8 [1,1,1,1]、[2,1,1]、[1,2,1]、[1,1,2]、[1,3]、[2,2]、[3,1]、[4] =2*2+4
......... f(n)=2f(n-2)+f(n-1)
package arraydemo;
/**
* @author wyl
* @time 2018年8月21日下午8:48:34
*/
public class Solution10 {
public static void main(String[] args) {
System.out.println(JumpFloorII(3));
}
public static int JumpFloorII(int target) {
if (target<=0) {
return 0;
}else if (target==1) {
return 1;
}else if (target==2) {
return 2;
}else {
return JumpFloorII(target-1)+2*JumpFloorII(target-2);
}
}
}
——————————————————————————————————————————————————————————
我们可以用2*1的小矩形横着或者竖着去覆盖更大的矩形。
请问用n个2*1的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?
矩形数 方法
1 1
2 2 [1,1]、[2]
3 3 [2,1]、[1,2]、[3]
4 5 [2,1,1]、[1,2,1]、[1,1,2]、[2,2]、[4]
......... f(n)=f(n-2)+f(n-1)
package arraydemo;
/**
* @author wyl
* @time 2018年8月21日下午8:48:34
*/
public class Solution11 {
public static void main(String[] args) {
System.out.println(RectCover(3));
}
public static int RectCover(int target) {
if (target<=0) {
return 0;
}else if (target==1) {
return 1;
}else if (target==2) {
return 2;
}else {
return RectCover(target-1)+RectCover(target-2);
}
}
}