输入一个字符串,按字典序打印出该字符串中字符的所有排列。 例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。
索引从第一位开始,把索引位置和自己以及自己以后的位置的字符交换,那么第一位可能情况就确定了.
依次往下,索引加1,继续确定后面位置可能情况.当确认的位置到了最后一个位置时候就可以输出了,因为它没得交换了!
另外这里存在一个可能存在重复元素的问题,我们把它当作正常元素看待即可,在最后存入list前进行判断就可以,或者我们用set的hash性质去重也是可以的
public class Permutation {
public ArrayList<String> Permutation(String str) {
ArrayList<String> list=new ArrayList<>();
getAll(str.toCharArray(),0,list);
Collections.sort(list,new myComp());
return list;
}
public void getAll(char[] chars,int index,ArrayList<String> list) {
if (index==chars.length-1){
if (!list.contains(new String(chars))){
list.add(new String(chars));
}
return;
}else {
for(int i=index;i<chars.length;i++){
swap(chars,index,i);
getAll(chars,index+1,list);
swap(chars,index,i);
}
}
}
public void swap(char[] chars,int indexa,int indexb){
char temp=chars[indexa];
chars[indexa]=chars[indexb];
chars[indexb]=temp;
}
class myComp implements Comparator<String>{
@Override
public int compare(String o1, String o2) {
return (o1+o2).compareTo(o2+o1);
}
}
}