Title Description
We can use the small rectangle of 2*1 to cover the larger rectangle horizontally or vertically. What is the total number of ways to cover a large rectangle of 2*n with n 2*1 small rectangles without overlapping?
Enter a description
A large Rectangle
Output description
Number of methods covered
Problem analysis
The total number of methods with a small rectangle of n 2*1 overlay without overlap is f (n)
When N=1, the apparent f (1) = 1;
When n=2, only two are horizontal or two are upright, there is f (2) = 2;
When the number of small rectangles is n, it overrides the large rectangle of the 2*n . There are only two ways to put the first step:
① upright, then the rest of the total number of places is f (n-1)
② is placed sideways, then the rest of the total is F (n-2). Because the block underneath it is also determined by its placement (it must be a small rectangle that is placed sideways).
It is easy to see that the Fibonacci sequence is fulfilled.
Fibonacci sequence (Fibonacci sequence), also known as the Golden Divide series
Mathematically, the Fibonacci sequence is defined as a recursive method: F (0) =0,f (1) =1,f (n) =f (n-1) +f (n-2) (n≥2,n∈n*)
Refers to a series of: 0, 1, 1, 2, 3, 5, 8, 13, 21, 、......
Recursive formulas can be derived:
| 1 (n=0)
F (n) = | 1 (n=1)
| F (n-1) +f (n-2) (n>=2)
Solution One (Recursive) run time: 924ms Memory: 654k
publicclass Solution { publicintRectCover(int target) { if(target<=1return1; return RectCover(target-1)+RectCover(target-2); }}
Recursive efficiency is not high, repeat the calculation of more, such as:
f(4) = f(3) + f(2); = f(2) + f(1) + f(1) + f(0); = f(1) + f(0) + f(1) + f(1) + f(0);
F (4) is calculated three times F (1) and two times F (0), which is obviously not possible.
Solution two (dynamic programming) Run time: 29ms Memory: 629k
public Class Solution {public int rectcover (int target) {if (Target<=1 ) return 1 ; int i =1 ; //f (0) int J =1 ; //f (1) for (; Target>=2 ; target--) {j+=i; I=j-i; } return J; }}
Obviously this is a lot faster, n>=2, according to F (n) =f (n-1) +f (n-2) to calculate sequentially, and finally come to F (target) and return.
[Sword Point offer] Rectangle overlay