题目来源:https://www.nowcoder.com/practice/72a5a919508a4251859fb2cfb987a0e6?tpId=13&&tqId=11163&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
题目描述
我们可以用21的小矩形横着或者竖着去覆盖更大的矩形。请问用n个21的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?
比如n=3时,2*3的矩形块有3种覆盖方法:
题解
解题思路:
n=1,F(n)=1
n=2,F(n)=2
n=3,F(n)=3
n=4,F(n)=5
F(n)=F(n-1)+F(n-2)
代码实现
/**
* 方法1:递归
* 规律 F(n)=F(n-1)+F(n-2)
*/
public class Solution {
public int RectCover(int target) {
if (target <= 0) {
return 0;
} else if (target == 1 || target == 2) {
return target;
}
return RectCover(target - 1) + RectCover(target - 2);
}
}
/**
* 方法2:自底向上,动态规划
* 规律 F(n)=F(n-1)+F(n-2),n>2
*/
public class Solution {
public int RectCover(int target) {
if (target <= 0) {
return 0;
} else if (target == 1 || target == 2) {
return target;
}
int[] dp = new int[target + 1];
dp[0] = 0;
dp[1] = 1;
dp[2] = 2;
for (int i = 3; i <= target; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[target];
}
}