题目描述:有一长度为N(1<=N<=10)的地板,给定两种不同瓷砖:一种长度为1,另一种长度为2,数目不限。要将这个长度为N的地板铺满,一共有多少种不同的铺法?列出所有的铺地砖的铺法。
eg:
4=1+1+1+1
4=2+1+1
4=1+2+1
4=1+1+2
4=2+2
package 蓝桥杯;
import java.util.ArrayList; // 导入ArrayList类,用于存储结果
import java.util.List; // 导入List接口,用于类型转换
import java.util.Scanner;
public class day08 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int N=sc.nextInt();
List<List<Integer>> result = new ArrayList<>(); // 创建一个空的ArrayList,用于存储所有可能的铺法
backtrack(result, new ArrayList<>(), N, 1, 2); // 调用backtrack函数,开始回溯搜索
System.out.println("共有 " + result.size() + " 种铺法"); // 输出结果:共有多少种铺法
for (List<Integer> path : result) { // 遍历所有可能的铺法
System.out.print(" ");
for (int i = 0; i < path.size(); i++) { // 遍历当前铺法的所有瓷砖
System.out.print(path.get(i)); // 输出当前瓷砖的值
if (i < path.size() - 1) { // 如果当前瓷砖不是最后一个瓷砖
System.out.print("+");
}
}
System.out.println(" ");
}
}
private static void backtrack(List<List<Integer>> result, List<Integer> path, int n, int tile1, int tile2) { // 定义回溯函数backtrack
if (n == 0) { // 如果当前已经铺满地板
result.add(new ArrayList<>(path)); // 将当前铺法添加到结果列表中
return; // 结束当前递归分支
}
if (tile1 <= n) { // 如果第一种瓷砖的长度小于等于剩余需要铺的长度
path.add(tile1); // 将第一种瓷砖添加到当前铺法中
backtrack(result, path, n - tile1, tile1, tile2); // 继续回溯搜索,剩余需要铺的长度减去第一种瓷砖的长度
path.remove(path.size() - 1); // 移除刚刚添加的第一种瓷砖,回溯到上一步
}
if (tile2 <= n) { // 如果第二种瓷砖的长度小于等于剩余需要铺的长度
path.add(tile2); // 将第二种瓷砖添加到当前铺法中
backtrack(result, path, n - tile2, tile1, tile2); // 继续回溯搜索,剩余需要铺的长度减去第二种瓷砖的长度
path.remove(path.size() - 1); // 移除刚刚添加的第二种瓷砖,回溯到上一步
}
}
}