矩形覆盖

题目描述

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


分析:

解题思路:归纳法(列举出n=1,2,3,4,5 总结规律)



得到:

f(1)=1

f(2)=2

f(3)=3

f(4)=5

f(5)=8

即:n>2时,f(n)=f(n-1) + f(n-2)


代码1:使用递归

public class Solution {
public int RectCover(int target) {
if(target == 1){
return 1;
}else if(target == 2){
return 2;
}else{
return RectCover(target - 1) + RectCover(target - 2);
}
    }
public static void main(String[] args) {
Solution s = new Solution();
System.out.println(s.RectCover(5));
}
}


代码2

public class Solution1 {
public int RectCover(int target) {
int one = 1;
int two = 2;
if(target == 1){
return 1;
}
if(target == 2){
return 2;
}
int result = 0;
for(int i = 3;i <= target;i++){
result = one + two;
one = two;
two = result;
}
return result;
}
public static void main(String[] args) {
Solution1 s = new Solution1();
System.out.println(s.RectCover(5));
}
}


发布了79 篇原创文章 · 获赞 19 · 访问量 12万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章