Ray又對數字的列產生了興趣:
現有四張卡片,用這四張卡片能排列出很多不同的4位數,要求按從小到大的順序輸出這些4位數,
Input每組資料占一行,代表四張卡片上的數字(0<=數字<=9),如果四張卡片都是0,則輸入結束,
Output對每組卡片按從小到大的順序輸出所有能由這四張卡片組成的4位數,千位數字相同的在同一行,同一行中每個四位數間用空格分隔,
每組輸出資料間空一行,最后一組資料后面沒有空行,
Sample Input
1 2 3 4 1 1 2 3 0 1 2 3 0 0 0 0
Sample Output
1234 1243 1324 1342 1423 1432 2134 2143 2314 2341 2413 2431 3124 3142 3214 3241 3412 3421 4123 4132 4213 4231 4312 4321 1123 1132 1213 1231 1312 1321 2113 2131 2311 3112 3121 3211 1023 1032 1203 1230 1302 1320 2013 2031 2103 2130 2301 2310 3012 3021 3102 3120 3201 3210
注意:1.第一位不能為0 2.重復數字的處理 3.格式控制
代碼:
import java.util.Arrays; import java.util.Scanner; public class Main{ static final int N=15; static int a[]=new int[N]; static int b[]=new int[N]; static int w;//控制換行和空格 static int last;//用來記錄第一個數字,不同就要換行 static boolean vis[]=new boolean[N]; static void dfs(int t){ if(t==4){ if(b[0]==0) return;//第一位不能為0 if(w!=0 && b[0]==last) System.out.print(" "); if(w!=0 && b[0]!=last)System.out.println(); for(int i=0;i<4;i++) System.out.print(b[i]); w++; last=b[0]; } for(int i=0;i<4;i++){ if(!vis[i]){ vis[i]=true; b[t]=a[i]; dfs(t+1); vis[i]=false; while(a[i]==a[i+1]) i++;//重復數字 } } } public static void main(String[] args) { Scanner scan=new Scanner(System.in); boolean flag=false; while(scan.hasNext()){ for(int i=0;i<4;i++) a[i]=scan.nextInt(); if(a[0]==0 && a[1]==0 && a[2]==0 && a[3]==0) break; Arrays.sort(a,0,4); Arrays.fill(vis, false);
//控制每個測驗樣例之間的換行空格 if(flag) System.out.println(); flag=true;
w=0; dfs(0);
System.out.println();//換行注意 } } }
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/100441.html
標籤:其他
上一篇:kuangbin專題專題十一 網路流 POJ 3436 ACM Computer Factory
下一篇:n皇后問題(dfs-擺放問題)
