輸出1,2,2,3,4,5的所有排列組合,4不能在第三位,3和5不能相鄰


一個比較優化的算法

  1. import java.util.Set;   
  2. import java.util.TreeSet   
  3. /**  
  4.  * 原始版本沒有考慮重複問題,我進行了修正.<br>  
  5.  * 此算法的精華就是,讓一個字符串的所有位置都進行互換,<br>  
  6.  * 這樣就產生了所有可能出現的字符串。  
  7.  *   
  8.  * @author 趙學慶,nicky_zs <A href="http://www.java2000.net">www.java2000.net</A>  
  9.  */  
  10. public class MyTest {   
  11.   public static void main(String args[]) {   
  12.     char[] number = new char[] { '1''2''2''3''4''5' };   
  13.     perm(number, 0, number.length - 1);   
  14.     System.out.println(set.size());   
  15.     int cols = 10;   
  16.     for (String s : set) {   
  17.       System.out.print(s + " ");   
  18.       if (cols-- == 1) {   
  19.         System.out.println();   
  20.         cols = 10;   
  21.       }   
  22.     }   
  23.   }   
  24.   public static void addNumber(String str) {   
  25.     set.add(str);   
  26.   }   
  27.   public static Set<String> set = new TreeSet<String>();   
  28.   public static void perm(char[] n, int beg, int end) {   
  29.     if (beg == end) {   
  30.       String result = String.valueOf(n);   
  31.       if (n[2] == '4')   
  32.         return;   
  33.       if (result.contains("35") || result.contains("53"))   
  34.         return;   
  35.       addNumber(String.valueOf(n));   
  36.       return;   
  37.     }   
  38.     for (int i = beg; i <= end; ++i) {   
  39.       swap(n, beg, i);   
  40.       perm(n, beg + 1, end);   
  41.       swap(n, beg, i);   
  42.     }   
  43.   }   
  44.   public static int number = 0;   
  45.   public static void swap(char[] n, int a, int b) {   
  46.     char temp = n[a];   
  47.     n[a] = n[b];   
  48.     n[b] = temp;   
  49.   }   
  50. }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章