Sword refers to offer-supplement 3. Rectangular coverage-analysis and code [Java]
1. Title
We can use 2 * 1 small rectangles horizontally or vertically to cover larger rectangles. How many ways are there to cover a large 2 * n rectangle with n small 2 * 1 rectangles without overlap?
Two, analysis and code
1. Dynamic programming
(1) Thinking
When n> 2, its covering method can be regarded as the covering method of the large rectangle of n-1 plus 1 small vertical rectangle or the covering method of the large rectangle of n-2 plus 2 small horizontal rectangles , That is, F(n) = F(n-1) + F(n-2). According to this characteristic, it can be solved by combining with dynamic programming method.
(2) Code
public class Solution {
public int RectCover(int target) {
if (target < 3)
return target;
int [] ans = new int[target + 1];
ans[1] = 1;
ans[2] = 2;
for (int i = 3; i <= target; i++)
ans[i] = ans[i - 1] + ans[i - 2];
return ans[target];
}
}
(3) Results
Running time: 13 ms, occupying 9292 k of memory.
Three, other
Nothing.