跳台阶+变态跳+矩形覆盖——offer

12 篇文章 0 订阅
 一只青蛙一次可以跳上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);
	   }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Baymax_wyl

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值