【剑指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

猜你喜欢

转载自www.cnblogs.com/Blog-cpc/p/12486406.html
今日推荐