小明最近喜欢搭数字积木,
一共有 10 块积木,每个积木上有一个数字,0~9。
搭积木规则:
每个积木放到其它两个积木的上面,并且一定比下面的两个积木数字小。
最后搭成 4 层的金字塔形,必须用完所有的积木。
下面是两种合格的搭法:
0
1 2
3 4 5
6 7 8 9
0
3 1
7 5 2
9 8 6 4
请你计算这样的搭法一共有多少种?
- public class Main {
- static int ans;
- static int[] book = new int[11];
- static int[][] map = new int[5][5];
- public static void main(String[] args) {
- dfs(4, 0); // Fourth Layer
- System.out.println(ans);
- }
- static void dfs(int layer, int idx) {
- if (layer == 0) {
- ans++;
- } else {
- for (int i = 0; i <= 9; i++) {
- if (layer == 4) {
- if (book[i] == 0) {
- book[i] = 1;
- map[layer][idx] = i;
- dfs(idx + 1 == layer ? layer - 1 : layer, (idx + 1) % layer);
- book[i] = 0;
- }
- } else {
- if (check(layer, idx, i)) {
- book[i] = 1;
- map[layer][idx] = i;
- dfs(idx + 1 == layer ? layer - 1 : layer, (idx + 1) % layer);
- book[i] = 0;
- }
- }
- }
- }
- }
- private static boolean check(int layer, int idx, int i) {
- return book[i] == 0 && i < map[layer + 1][idx] && i < map[layer + 1][idx + 1];
- }
- }