输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cb
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;
}
}