給定六個數字:1、2、3、3、5、6,試編程求出滿足下述要求的,用這六個數字組成的6位數的個數:
1) 兩個數字3不能相鄰,例如653321不允許
2) 數字5不能在第5位,例如132356不允許
我寫了個運用窮舉法進行篩選的代碼,呵呵,感覺實現得很不優雅……
public class Test {
public static void main(String[] args) {
int num=0;
int[] arr={1,2,3,4,5,6}; //先把3換成4初篩
for(int i=0;i<6;i++){
for(int j=0;j<6;j++){
if(j==i)
continue; //如果數組的這個位置已經佔了,跳出循環
for(int k=0;k<6;k++){
if(k==i||k==j)
continue;
for(int l=0;l<6;l++){
if(l==i||l==j||l==k)
continue;
for(int m=0;m<6;m++){
if(m==i||m==j||m==k||m==l)
continue;
for(int n=0;n<6;n++){
if(n==i||n==j||n==k||n==l||n==m)
continue;
String str=""+arr[i]+arr[j]+arr[k]+arr[l]+arr[m]+arr[n]; //形成數字串
if(str.indexOf("5")==4) //去掉數字5在位置5的
continue;
if(str.indexOf("4")>str.indexOf("3")) //數字3、數字4交換位置的只取一個
continue;
str=str.replace('4','3'); //數字4換成數字3
if(str.indexOf("33")>=0)
continue; //去掉33相鄰的數字串
num++;
System.out.print(str+" ");
if(num%10==0)
System.out.println();
}
}
}
}
}
}
System.out.println(num+"個");
}
}