剑指offer--矩形覆盖

来源:互联网 发布:cf卡海豹突击队软件 编辑:程序博客网 时间:2024/06/06 13:01

题目描述

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

分类:数组

解法1:斐波那契数列
[java] view plain copy
  1. public class Solution {  
  2.     public int RectCover(int target) {  
  3.         if(target==1return 1;  
  4.         if(target==2return 2;  
  5.         return RectCover(target-1)+RectCover(target-2);  
  6.     }  
  7. }  

下面是迭代算法,用空间换时间

[java] view plain copy
  1. public class Solution {  
  2.     public int RectCover(int target) {  
  3.         if(target==0||target==1return 1;    
  4.         if(target==2return 2;    
  5.         int pre  = 1;    
  6.         int next = 2;    
  7.         int t = 0;    
  8.         int i =2;    
  9.         while(i<target){    
  10.             t = pre+next;    
  11.             pre = next;    
  12.             next = t;    
  13.             i++;    
  14.         }           
  15.         return next;    
  16.     }  
  17. }  

原文链接  http://blog.csdn.net/crazy__chen/article/details/44985287

原创粉丝点击