您的位置:首页 > 其它

矩形覆盖

2017-07-09 18:30 239 查看
我们可以用2*1的小矩形横着或者竖着去覆盖更大的矩形。

请问用n个2*1的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?

本题实质是斐波拉契数列,类似问题——跳台阶斐波拉契数列

/**
* 解法一——递归解法
*
*/
public class Solution {

public static void main(String[] args) {
Solution solution = new Solution();
System.out.print("请输入n的值:");
@SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
int n = in.nextInt();
System.out.println("组合方法:" + solution.RectCover(n));

}

public int RectCover(int target) {
return (target <= 2) ? target : RectCover(target - 1) + RectCover(target - 2);
}
}


/**
* 解法一——一般循环解法
*
*/
public class Solution {

public static void main(String[] args) {
Solution solution = new Solution();
System.out.print("请输入n的值:");
@SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
int n = in.nextInt();
System.out.println("组合方法:" + solution.RectCover(n));

}

public int RectCover(int target) {
int a = 1;
int b = 2;
int result = 0;

if(target == 1) {
result = 1;
} else if(target == 2) {
result =2;
} else {
for(int i = 0; i < target - 2; i++) {
result = a + b;
a = b;
b = result;
}
}

return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息