输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串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