题目描述:
小明最近喜欢搭数字积木,
一共有10块积木,每个积木上有一个数字,0~9。
搭积木规则:
每个积木放到其它两个积木的上面,并且一定比下面的两个积木数字小。
最后搭成4层的金字塔形,必须用完所有的积木。
下面是两种合格的搭法:
0
1 2
3 4 5
6 7 8 9
0
3 1
7 5 2
9 8 6 4
请你计算这样的搭法一共有多少种?
请填表示总数目的数字。
注意:你提交的应该是一个整数,不要填写任何多余的内容或说明性文字。
正确算法:
此题的答案是:768
这道题目我用的是暴力破解,将每一层的每个元素都输出,分析题目可以得出第一层只能是0,而第二层的取值范围是1~4,第三层的取值范围是2~7,第四层的取值范围是3~9,所以用9层for循环就可以写出来了。当然也可以将每一层的取值范围设成0~9,让程序把所有的情况都跑一遍。
public class 搭积木 {public static void main(String[] args) {int count = 0;boolean arr[] = new boolean[10];for (int a = 1; a <= 4; a++) {//2arr[a] = true;for (int b = 1; b <= 4; b++) {//2if (arr[b]) {continue;}arr[b] = true;for (int c = 2; c <= 7; c++) {//3if (arr[c] || c < a) {continue;}arr[c] = true;for (int d = 2; d <= 7; d++) {//3if (arr[d] || d < a || d < b) {continue;}arr[d] = true;for (int e = 2; e <= 7; e++) {//3if (arr[e] || e < b) {continue;}arr[e] = true;for (int f = 3; f <= 9; f++) {//4if (arr[f] || f < c) {continue;}arr[f] = true;for (int g = 3; g <= 9; g++) {//4if (arr[g] || g < c || g < d) {continue;}arr[g] = true;for (int h = 3; h <= 9; h++) {//4if (arr[h] || h < d || h < e) {continue;}arr[h] = true;for (int i = 3; i <= 9; i++) {//4if (arr[i] || i < e) {continue;}count++; // System.out.println("第"+count+"种:"); // System.out.println(" "+" "+a+" "+b); // System.out.println(" "+c+" "+d+" "+e); // System.out.println(f+" "+g+" "+h+" "+i); // System.out.println();String str = " " + " " + a + " " + b + "\n" + " " + c + " " + d + " " + e+"\n"+ f + " " + g + " " + h + " " + i;}arr[h] = false;}arr[g] = false;}arr[f] = false;}arr[e] = false;}arr[d] = false;}arr[c] = false;}arr[b] = false;}arr[a] = false;}System.out.println(count);} }