問題要求:算法
給出幾個字符,輸出字符的全部排列組合。ide
如:已知 a b,可得出ab; bc;函數
已知 a b c,可得出abc; acb; cab; bac; bca; cba;ui
實現思路(1):spa
遞歸算法,把集合做爲字符串,每次取出一個字符,分別插入已經排列好的組合的空擋(頭部,每兩個字符間,尾部),造成新組合,再不斷循環過程,直到最後一個字符插入時,輸出。code
1 package combination; 2 /** 3 * 4 * @author xy.hong 5 * 輸出一個字符串裏面全部字符的排列組合 6 */ 7 8 public class Combination { 9 private StringBuilder myString; //字符集合做爲字符串 10 private int length; //字符集合的數量 11 private int num=0; //記錄排列的序號,用於驗證排列的數量是否正確,已知字符數,則排列數量可求。從而驗證程序有無錯誤 12 13 public Combination(StringBuilder s){ //構造函數 14 myString=s; 15 length=s.length(); 16 } 17 18 public void printStrings(){ //調用遞歸函數 19 comb(0,new StringBuilder("")); 20 } 21 22 /* 23 * void comb( 下標, 已經排列好的某個數列) //方法說明 24 */ 25 private void comb(int idex,StringBuilder sb){ 26 StringBuilder s =new StringBuilder(sb); 27 28 if(idex==length){ //若是字符已經取完,則能夠輸出 29 System.out.print(""+(++num)+":"+s+" "); 30 return; 31 } 32 int l=sb.length(); //已排序好的字符串的長度 33 for(int i=0; i<=l; i++){ //使用循環分別插入空擋 34 s.insert(i, myString.charAt(idex)); //插入字符 35 comb(idex+1, s); //遞歸 36 s.deleteCharAt(i); //取出插入字符,插入到下個位置 37 38 } 39 } 40 41 42 public static void main(String[] args) { 43 // TODO Auto-generated method stub 44 StringBuilder s = new StringBuilder("abc"); //構造要排列的字符 45 Combination a = new Combination(s); //構造對象 46 a.printStrings(); //輸出字符 47 } 48 49 }
缺點:運算量大,遞歸太慢慢慢慢慢慢慢慢慢慢慢慢慢慢慢了。對象
撰寫時間:2017-08-09 14:51:49blog