[Swords offer] Matrix coverage

Topic description:

We can use 2*1 small rectangles to cover larger rectangles horizontally or vertically. How many ways are there to cover a large 2*n rectangle with n small rectangles of 2*1 without overlapping?

solution:

You can consider recursion. There are two ways to cover the large rectangle each time. The first one can be covered vertically, so 2 rectangles can be covered each time, and the second one can be covered horizontally, then it will definitely cover 4 rectangles each time. Because the top is covered with horizontal, the bottom 2 rectangles must be placed horizontally. The expression can be deduced: f(n) = f(n-1) + f(n-2)
The recursive boundary conditions are ① only the last two vertical rectangles are left, and there is only one solution; ② there are only four horizontal rectangles left, and there can be two solutions.
0, n<=0;
1, n==1;
2, n==2;
f(n-1) + f(n-2), other
Code:
import java.util.Scanner;

/* We can use 2*1 small rectangles to cover larger rectangles horizontally or vertically.
 * How many ways are there to cover a large 2*n rectangle with n small 2*1 rectangles without overlapping?
 */
public class RectCover {

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		while(in.hasNext()){
			int n = in.nextInt();
			int result = rectCover(n);
			System.out.println(result);
		}
	}
	
	 public static int rectCover(int target) {
	        if(target <= 0){
	        	return 0;
	        }
	        if(target == 1){
	            return 1;
	        }
	        if(target == 2){
	            return 2;
	        }        
	        return rectCover(target-1) + rectCover(target-2);
	    }
}




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325496358&siteId=291194637