1. 程式人生 > >給定一個字串,輸出所有的排列組合方式

給定一個字串,輸出所有的排列組合方式

去參加一個筆試,遇到一個問題就是給定字串"123456"要我寫程式輸出所有的排列組合方式,當時頭很大,一直想不出來,於是很磋的寫了迴圈。回來了好好想了想,參考網上的資料,今天真正理解並且自己寫了出來。是用遞迴,理解為每次都是求已知的字串與未排列的字串的組合!

/*
2011-9-9
author:BearFly1990
*/
package temp;

public class RecursionString {
    public static void main(String[] args) {
        String b = "123456";
        doit("",b);
    }
    public static void doit(String a,String b){
        if(a.length()== 6){
          System.out.println(a);
        }else{ 
           for(int i = 0; i< b.length(); i++){
               String tempa = new String(a);
               String tempb = new String(b);
               doit(tempa+tempb.charAt(i),new StringBuilder(tempb)
                   .deleteCharAt(i).toString());
           }
        }
    }
  
    
}