1、问题描述
小明最近喜欢搭数字积木,
一共有10块积木,每个积木上有一个数字,0~9。
搭积木规则:
每个积木放到其它两个积木的上面,并且一定比下面的两个积木数字小。
最后搭成4层的金字塔形,必须用完所有的积木。
下面是两种合格的搭法:
0
1 2
3 4 5
6 7 8 9
0
3 1
7 5 2
9 8 6 4
请你计算这样的搭法一共有多少种?
2、代码实现
public class Main{
static int ans = 0;
public static void main(String[] args) {
int[] arr = {0,1,2,3,4,5,6,7,8,9};
arrange(arr,0,arr.length - 1);
System.out.println(ans);
}
//全排列
public static void arrange(int[] arr,int from,int to) {
if(from == to) {
//这些if就是条件
if(arr[0] == 0) {
if(arr[1] < arr[3] && arr[1] < arr[4] && arr[2] < arr[4] && arr[2] < arr[5]) {
if(arr[3] < arr[6] && arr[3] < arr[7] && arr[4] < arr[7] && arr[4] < arr[8] && arr[5] < arr[8] && arr[5] < arr[9]) {
ans++;
}
}
}
return;
}else {
for(int i = from;i <= to;i++) {
swap(arr,i,from);
arrange(arr,from + 1,to);
swap(arr,i,from);
}
}
}
public static void swap(int[] arr,int from,int to) {
int temp = arr[from];
arr[from] = arr[to];
arr[to] = temp;
}
}