蓝桥杯搭积木

来源:互联网 发布:耽美小说的软件 编辑:程序博客网 时间:2024/04/27 23:13

题目

搭积木
小明最近喜欢搭数字积木,
一共有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 2

3 4 5

6 7 8 9的形式

这样把它存入一个二维数组,从上到下,录入值,每次录入的值只需要满足比上方和左上方大就行了!


代码如下:

static int[] v = new int[10];static int[][] s = new int[4][4];static int sum = 0;public static void main(String[] args) {s[0][0] = 0;s(1);System.out.println(sum);}public static void s(int code){if(code==10) {sum++;return;}for (int i = 1; i < 10; i++) {if(v[i]!=0) continue;else {int c=0,t=0;switch (code) {case 1:t = 1;c=0;break;case 2:t = 1;c=1;break;case 3:t = 2;c=0;break;case 4:t = 2;c=1;break;case 5:t = 2;c=2;break;case 6:t = 3;c=0;break;case 7:t = 3;c=1;break;case 8:t = 3;c=2;break;case 9:t = 3;c=3;break;}s[t][c] = i;if(s[t][c]<s[t-1][c]){continue;}if(c-1>=0){if(s[t][c]<s[t-1][c-1]){continue;}}v[i] = 1;s(code+1);v[i] = 0;}}}


0 0
原创粉丝点击