In fact, looking for the law, you can find that it is a Fibonacci sequence, which can be written in recursive and non-recursive ways.
For the case of n=4, let’s first look at how to put the first block on the left. There are two ways. The first is to put it vertically, leaving the position of 3*2, and the remaining position is the result of n=3, and the second The kind is placed horizontally, because it is placed horizontally and the area below it can only be placed horizontally. The remaining position is the result of n=2;
so it can be seen that f[ n] = f[ n-1]+ f[ n-2];
1. Non-recursive
class Solution {
public:
int rectCover(int number) {
int f[number+1];
f[0] = 0;
f[1] = 1; f[2] = 2;
for(int i=3;i<=number;i++){
f[i]=f[i-1]+f[i-2];
}
return f[number];
}
};
2. Recursion
class Solution {
public:
int rectCover(int number) {
int f[number+1];
f[0] = 0;
f[1] = 1; f[2] = 2;
for(int i=3;i<=number;i++){
f[i]=f[i-1]+f[i-2];
}
return f[number];
}
};
The time for recursive writing is actually shorter.