Prove safety offer10: 2 * 1 small rectangle of sideways or vertically to cover large rectangular 2 * n, a total of how many ways?

1. Title Description

  We can use a small rectangle 2 * 1 sideways or vertically to cover a larger rectangle. Will the small rectangle of n 2 * 1 coverage without overlap a large rectangle 2 * n, a total of how many ways?

2. The ideas and methods

  Thinking :( x * y comes below a rectangular, x wide, y is long, fixed at easy understanding) assume a rectangular 2 × n, then put the first two small rectangular discharge method: Put 2 × 1 or 1 × 2 discharge, if it is meant to put in a 1 × 2 below it can only be put in a 1 × 2, 2 × 2 to form a square. Then we can be divided into two structures, one is the first 2 × 1 rectangular shape, and the second is the square of 2 × 2. 2 wide are not considered, having two options 1 and 2, you can convert the question is: length of the line segment n is 1 and the long length of line 2 of the composition, the number of total species composition method .

  The method of line segments of length n = (length after the first step to put a method consisting of the remaining line segment) + (2 after the first step to lengthen the remaining segments consisting of the method), i.e., F (n) = f (n-1) + f (n-2); 1,2,3,5,8 .... It is similar to a Fibonacci number .

3.C ++ core code

3.1 Non-recursive method

 1 class Solution {
 2 public:
 3     int rectCover(int number) {
 4         if(number<=2)
 5             return number;
 6         int f1 = 1;
 7         int f2 = 2;
 8         int result = 0;
 9         for(int i = 3; i <= number; i++){
10             result = f1 + f2;
11             f1 = f2;
12             f2 = result;
13         }
14         return result;
15     }
16 };
View Code

3.2 recursive method

Recursive less code, but is high time complexity. For now under a lot of storage space environment, it should save time.

1 class Solution {
2 public:
3     int rectCover(int number) {
4         if(number<=3)
5             return number;
6         return rectCover(number-2)+rectCover(number-1);
7     }
8 };
View Code

Reference material

https://blog.csdn.net/JMasker/article/details/86771720

Guess you like

Origin www.cnblogs.com/wxwhnu/p/11407400.html
Recommended