当前位置: 代码迷 >> J2SE >> java竞赛题解决思路
  详细解决方案

java竞赛题解决思路

热度:135   发布时间:2016-04-24 02:16:03.0
java竞赛题
用1、2、2、3、4、5这六个数字,用java写一个main函数,打印出所有不同的排列,如:512234等,
要求:"4"不能在第三位,"3"与"5"不能相连.

------解决方案--------------------
手快弄错题意再发:
Java code
    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;            }        }    }
  相关解决方案