您的位置:首页 > Web前端

【剑指Offer】10、 矩形覆盖

2020-03-31 19:41 736 查看

题目描述

我们可以用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

 

  • 点赞
  • 收藏
  • 分享
  • 文章举报
Blog_pc 发布了66 篇原创文章 · 获赞 0 · 访问量 285 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: