搭积木
小明最近喜欢搭数字积木,
一共有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 {
public static void main(String[] args) {
int count = 0;
for (int a = 0; a < 10; a++) {
for (int b = 0; b < 10; b++) {
for (int c = 0; c < 10; c++) {
for (int d = 0; d < 10; d++) {
for (int e = 0; e < 10; e++) {
for (int f = 0; f < 10; f++) {
for (int g = 0; g < 10; g++) {
for (int h = 0; h < 10; h++) {
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (a != b && a != c && a != d && a != e && a != f && a != g && a != h
&& a != i && a != j && b != c && b != d && b != e && b != f
&& b != g && b != h && b != i && b != j && c != d && c != e
&& c != f && c != g && c != h && c != i && c != j && d != e
&& d != f && d != g && d != h && d != i && d != j && e != f
&& e != g && e != h && e != i && e != j && f != g && f != h
&& f != i && f != j && g != h && g != i && g != j && h != i
&& h != j && i != j && a < b && a < c && b < d && b < e && c < e
&& c < f && d < g && d < h && e < h && e < i && f < i
&& f < j) {
count++;
}
}
}
}
}
}
}
}
}
}
}
System.out.println(count);
}
}
public class Main {
public static int[] a = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
public static int count = 0;
public static void f(int n) {
if (n == a.length) {
if (is_right()) {
count++;
}
}
for (int i = n; i < a.length; i++) {
int temp = a[i];
a[i] = a[n];
a[n] = temp;
f(n + 1);
temp = a[i];
a[i] = a[n];
a[n] = temp;
}
}
private static boolean is_right() {
if (a[0] != a[1] && a[0] != a[2] && a[0] != a[3] && a[0] != a[4] && a[0] != a[5] && a[0] != a[6] && a[0] != a[7]
&& a[0] != a[8] && a[0] != a[9] && a[1] != a[2] && a[1] != a[3] && a[1] != a[4] && a[1] != a[5]
&& a[1] != a[6] && a[1] != a[7] && a[1] != a[8] && a[1] != a[9] && a[2] != a[3] && a[2] != a[4]
&& a[2] != a[5] && a[2] != a[6] && a[2] != a[7] && a[2] != a[8] && a[2] != a[9] && a[3] != a[4]
&& a[3] != a[5] && a[3] != a[6] && a[3] != a[7] && a[3] != a[8] && a[3] != a[9] && a[4] != a[5]
&& a[4] != a[6] && a[4] != a[7] && a[4] != a[8] && a[4] != a[9] && a[5] != a[6] && a[5] != a[7]
&& a[5] != a[8] && a[5] != a[9] && a[6] != a[7] && a[6] != a[8] && a[6] != a[9] && a[7] != a[8]
&& a[7] != a[9] && a[8] != a[9] && a[0] < a[1] && a[0] < a[2] && a[1] < a[3] && a[1] < a[4]
&& a[2] < a[4] && a[2] < a[5] && a[3] < a[6] && a[3] < a[7] && a[4] < a[7] && a[4] < a[8] && a[5] < a[8]
&& a[5] < a[9]) {
return true;
}
return false;
}
public static void main(String[] args) {
f(0);
System.out.println(count);
}
}
答案:768