今有7对数字:两个1,两个2,两个3,...两个7,把它们排成一行。
要求,两个1间有1个其它数字,两个2间有2个其它数字,以此类推,两个7之间有7个其它数字。如下就是一个符合要求的排列:
要求,两个1间有1个其它数字,两个2间有2个其它数字,以此类推,两个7之间有7个其它数字。如下就是一个符合要求的排列:
17126425374635
当然,如果把它倒过来,也是符合要求的。
请你找出另一种符合要求的排列法,并且这个排列法是以74开头的。
注意:只填写这个14位的整数,不能填写任何多余的内容,比如说明注释等。
分析:由题目的意思就是要找出一个序列是 74****4*7*****这样的,直接深度搜索。
public class Main {
public static int[] a = new int[] {7,4,0,0,0,0,4,0,7,0,0,0,0,0};
public static boolean ok(int step,int x)
{
if(step+x+1>=14) return false;
if(a[step+x+1]!=0) return false;
for(int i=0;i<step;i++)
{
if(a[i]==x) return false;
}
return true;
}
public static void dfs(int step)
{
if(step==14)
{
for(int i=0;i<=13;i++)
{
System.out.print(a[i]);
}
return;
}
if(a[step] != 0)
{
dfs(step+1);
}else{
for(int x=1;x<=7;x++)
{
if(ok(step,x))
{
a[step] = x;
a[step+x+1] = x;
dfs(step+1);
a[step+x+1] = 0;
a[step] = 0; //74151643752362
}
}
}
}
public static void main(String[] args) {
dfs(0);
}
}