zoukankan      html  css  js  c++  java
  • hdu1716--全排列(dfs+有重复数字+输出格式)

    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();//换行注意 } } }
  • 相关阅读:
    文艺青年会看这本《迷局》么?
    看文艺青年怎么玩微信客户端
    Sublime Text有哪些使用技巧(转)
    C++ 关键字 explicit, export, mutable
    move语义和右值引用
    C++11 std::function用法
    function adapter(函数适配器)和迭代器适配器
    for_each()的返回值
    C++11的一些新特性
    setw和setfill控制输出间隔
  • 原文地址:https://www.cnblogs.com/qdu-lkc/p/12238753.html
Copyright © 2011-2022 走看看