【剑指Offer】10、 矩形覆盖

题目描述

我们可以用21的小矩形横着或者竖着去覆盖更大的矩形。请问用n个21的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?

题解一:递归
 1 //类似于斐波那契,递归
 2     public static int RectCover(int target) {
 3         if(target<=0){
 4             return 0;
 5         }else if (target == 1 || target == 2) {
 6             return target;
 7         }else {
 8             return RectCover(target-1) + RectCover(target-2);
 9         }
10     }
题解二:非递归
 1 public static int RectCover01(int target) {
 2         if(target <= 2) {
 3             return target;
 4         }
 5         int one = 1;
 6         int two = 2;
 7         int result = 0;
 8         for (int i = 3; i <= target; i++) {
 9             result = one + two;
10             one = two;
11             two = result;
12         }
13         return result;
14     }

测试:

 1 public static void main(String[] args) {
 2         Scanner scanner = new Scanner(System.in);
 3         while (scanner.hasNext()){
 4             int anInt = scanner.nextInt();
 5             int cover = RectCover(anInt);
 6             System.out.println(cover);
 7         }
 8     }
 9 输入:0 1 2 3 4 5 6  7  8  9  10
10 输出:0 1 2 3 5 8 13 21 34 55 89

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值