用1、2、2、3、4、5这六个数字,用java写一个main函数,打印出所有不同的排列,如:512234等,
要求:"4"不能在第三位,"3"与"5"不能相连.

解决方案 »

  1.   

    没人答,哈哈40给我好了 public static void main(String[] args) {
    int[] a = {1,2,2,3,4,5};
    TreeMap<String,String> tm = new TreeMap<String,String>();
    f(a,0,"",tm);
    Iterator<String> it = tm.keySet().iterator();
    while(it.hasNext()) {
    System.out.println(it.next());
    }
    }

    public static void f(int[] a,int n,String str,TreeMap<String,String> tm) {
    if(n==a.length-1) {
    String str_2 = str+a[n];
    if(!str_2.matches("\\d*?35\\d*?|\\d*?53\\d*?")&&!str_2.matches("[\\d]{3}4\\d+")) {
    tm.put(str_2, str_2);
    }
    }
    else {
    for(int i = n;i<a.length;i++) {
    int test = a[n];
    a[n] = a[i];
    a[i] = test;
    String str_2 = str+a[n];
    f(a,n+1,str_2,tm);
    a[i] = a[n];
    a[n] = test;
    }
    }
    }
      

  2.   

    手快弄错题意再发: public static void main(String[] args) {
    int[] a = {1,2,2,3,4,5};
    TreeMap<String,String> tm = new TreeMap<String,String>();
    f(a,0,"",tm);
    Iterator<String> it = tm.keySet().iterator();
    while(it.hasNext()) {
    System.out.println(it.next());
    }
    }

    public static void f(int[] a,int n,String str,TreeMap<String,String> tm) {
    if(n==a.length-1) {
    String str_2 = str+a[n];
    if(!str_2.matches("\\d*?35\\d*?|\\d*?53\\d*?")&&!str_2.matches("[\\d]{2}4\\d+")) {
    tm.put(str_2, str_2);
    }
    }
    else {
    for(int i = n;i<a.length;i++) {
    int test = a[n];
    a[n] = a[i];
    a[i] = test;
    String str_2 = str+a[n];
    f(a,n+1,str_2,tm);
    a[i] = a[n];
    a[n] = test;
    }
    }
    }
      

  3.   

    TreeMap有自动过滤重复值的特性,每次获得一个新的字符串时用正则表达式式检验是否符合"4"在第三位,"3"与"5"相连。2个条件都否时,就用TreeMap保存。核心的排列组合算法就是非常经典的了,网上有一堆说明。