Rectangular coverage (Fibonacci)

Insert picture description here
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.
Insert picture description here

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];
    }
};

Insert picture description here
The time for recursive writing is actually shorter.

Guess you like

Origin blog.csdn.net/qq_43811879/article/details/110291766