小明最近喜欢搭数字积木,
一共有10块积木,每个积木上有一个数字,0~9。
搭积木规则:
每个积木放到其它两个积木的上面,并且一定比下面的两个积木数字小。
最后搭成4层的金字塔形,必须用完所有的积木。
下面是两种合格的搭法:
0
1 2
3 4 5
6 7 8 9
0
3 1
7 5 2
9 8 6 4
请你计算这样的搭法一共有多少种?
static int num = 0; public static void main(String[] args) { String str[] = {"1","2", "3", "4", "5", "6", "7", "8","9" }; permutation(str, 0, str.length); System.out.println(num); } static void swap(String[] str, int start, int end) { String tmep = str[start]; str[start] = str[end]; str[end] = tmep; } static void permutation(String[] str, int start, int end) { if (start == end - 1) { int a[][]; a = new int[4][]; a[0] = new int[1]; a[1] = new int[2]; a[2] = new int[3]; a[3] = new int[4]; a[0][0] = 0; a[1][0] = Integer.parseInt(str[0]);a[1][1] = Integer.parseInt(str[1]); a[2][0] = Integer.parseInt(str[2]);a[2][1] = Integer.parseInt(str[3]);a[2][2] = Integer.parseInt(str[4]); a[3][0] = Integer.parseInt(str[5]);a[3][1] = Integer.parseInt(str[6]);a[3][2] = Integer.parseInt(str[7]);a[3][3] = Integer.parseInt(str[8]); if(isshu(a)){ num++; } } else { for (int i = start; i < end; i++) { if (i == 0 && str[0].equals("0")) continue; swap(str, start, i); permutation(str, start + 1, end); swap(str, start, i); } } } static boolean isshu(int a[][]){ boolean b = false; if(a[0][0]<a[1][0]&&a[0][0]<a[1][1]/*a[0][0]*/ &&a[1][0]<a[2][0]&&a[1][0]<a[2][1]/*a[1][0]*/ &&a[1][1]<a[2][1]&&a[1][1]<a[2][2]/*a[1][1]*/ &&a[2][0]<a[3][0]&&a[2][0]<a[3][1]/*a[2][0]*/ &&a[2][1]<a[3][1]&&a[2][1]<a[3][2]/*a[2][1]*/ &&a[2][2]<a[3][2]&&a[2][2]<a[3][3]/*a[2][2]*/){ b = true; } return b; }
截图:
768