题目:我们可以用2 * 1的小矩形横着或者竖着去覆盖更大的矩形。请问用n个2 * 1的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?
由图和数学归纳法可推断出:f(n)来表示种类总数,则f(n) = f(n-1) + f(n-2);
通过对公式进行递归,可得出结果。
代码:
public class Solution {
public int RectCover(int target) {
int sum = 0;
if(target == 1){
return 1;
}
if(target == 2){
return 2;
}
if(target > 2){
int first = 1;
int second = 2;
int third = 0;
for(int i = 3;i <= target;i++){
third = first + second;
first = second;
second = third;
}
sum = third;
}
return sum;
}
public static void main(String[] args){
Solution solution = new Solution();
System.out.println(solution.RectCover(1));
System.out.println(solution.RectCover(3));
System.out.println(solution.RectCover(9));
}
}