Topic Source: Cattle passenger network - Offer to prove safety topics
topics Address: rectangular footprint
Title Description
We can use small rectangular sideways or vertically to cover a larger rectangle. Will the use of n small rectangles without overlapping a cover large rectangle, a total of how many ways?
For example n = 3, the
rectangular blocks has three kinds of coating method:
Analytical title
In fact, this type of problem, if you really do not know how to start, you may wish to consider the enumeration, in front of the small number of enumerated first, then guess what the law Yes. General formula may be considered are , Fibonacci number, the polynomial of n-related, the number of combinations, the number of Cattleya, Euler function ......
This look at this question, we first the case of a relatively small first enumerated in the following table:
n | 1 | 2 | 3 | 4 | 5 | 6 | … |
---|---|---|---|---|---|---|---|
result | 1 | 2 | 3 | 5 | 8 | 13 | … |
Look, do not lie to you now! This is not a Fibonacci number do? I do not pit you, but to provide an idea when you really can not start, do not quick to write What to enumerate these circumstances ......
Below is a positive solution time:
Refer to the discussion forums Follow explain the idea of big brother, suppose we have a large rectangle, when method when there is a seed, we first consider the first small rectangle pendulum method. There are the following two situations:
- Case 1: the following FIG placed on end, then the rest is formed of a rectangular a large rectangle, the coating method in this case has species.
* | |||||||
---|---|---|---|---|---|---|---|
* |
- Case 2: sideways placed below, in order to cover the space below it, the second small rectangle must be placed sideways at the bottom of it ,, then the rest of it forms a rectangle The large rectangle, the coating method in this case has species.
* | * | ||||||
---|---|---|---|---|---|---|---|
- | - |
So, we can know , recombination case, we can obtain the following recursive friends ~
这个递推式看烂了,这里就简单写常用的两种实现方式,详情可以参考上篇博客解法:斐波那契数列(四种解法)。
方法一:
面试别写型递推版实现,时间复杂度
。
public class Solution {
public int RectCover(int n) {
if (n < 3) {
return n;
}
return RectCover(n - 1) + RectCover(n - 2);
}
}
方法二:
面试推荐型,自底向上型循环求解,时间复杂度为
。
public class Solution {
public int RectCover(int n) {
if (n == 0) return 0;
int a = 1, b = 1;
for (int i = 1; i < n; i++) {
a = a + b;
b = a - b;
}
return a;
}
}
如果本文对你有所帮助,要记得点赞哦~