今有7对数字:两个1,两个2,两个3,...两个7,把它们排成一行。
要求,两个1间有1个其它数字,两个2间有2个其它数字,以此类推,两个7之间有7个其它数字。如下就是一个符合要求的排列:
17126425374635
当然,如果把它倒过来,也是符合要求的。
请你找出另一种符合要求的排列法,并且这个排列法是以74开头的。
注意:只填写这个14位的整数,不能填写任何多余的内容,比如说明注释等。
1 public class Main { 2 3 public static int[] a = new int[] { 7, 4, 0, 0, 0, 0, 4, 0, 7, 0, 0, 0, 0, 0 }; 4 5 public static boolean ok(int step, int x) { 6 if (step + x + 1 >= 14) 7 return false; 8 if (a[step + x + 1] != 0) 9 return false; 10 for (int i = 0; i < step; i++) { 11 if (a[i] == x)// 12 return false; 13 } 14 return true; 15 } 16 17 public static void dfs(int step) { 18 if (step == 14) { 19 for (int i = 0; i <= 13; i++) { 20 System.out.print(a[i]); 21 } 22 return; 23 } 24 if (a[step] != 0) {//a[step]不等于0的话 25 dfs(step + 1); 26 } else {//a[step]等于0 27 for (int x = 1; x <= 7; x++) { 28 if (ok(step, x)) { 29 a[step] = x; 30 a[step + x + 1] = x; 31 dfs(step + 1); 32 a[step + x + 1] = 0; 33 a[step] = 0; // 74151643752362 34 } 35 } 36 } 37 } 38 39 public static void main(String[] args) { 40 dfs(0); 41 } 42 }