輸入一個字符串,按字典序打印出該字符串中字符的所有排列。例如輸入字符串abc,則打印出由字符a,b,c所能排列出來的所有字符串abc,acb,bac,bca,cab和cba。


import java.util.*;
public class Solution {
    
     public void  Permutation(char[] chars,int pos,TreeSet<String> result){
        if(pos==chars.length){
            result.add(String.valueOf(chars));
        }
        
        for(int i=pos;i<chars.length;i++){
            char temp=chars[i];
            chars[i]=chars[pos];
            chars[pos]=temp;
            
            Permutation(chars,pos+1,result);
            
            temp=chars[i];
            chars[i]=chars[pos];
            chars[pos]=temp;
        }
    }
    
    public ArrayList<String> Permutation(String str) {
        ArrayList<String> result=new ArrayList<String>();
        TreeSet<String> temp=new TreeSet<String>();//防止相同的兩個元素“aa”
        if(str==null || str.length()==0) return result;
        char[] chars=str.toCharArray();
       
        Permutation(chars,0,temp);
        result.addAll(temp);
        return result;
    }
    
   
}
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM