暴力迭代,第n个字符及前面的字符形成的字符串的全排列要先计算第n-1个字符及前面字符形成的字符串的全排列
public ArrayList<String> Permutation(String str) {
ArrayList<String> res=new ArrayList<>();
if(str==null || str.length()==0){
return res;
}
char [] chars=str.toCharArray();
ArrayList<String> tmp1=new ArrayList<>();
ArrayList<String> tmp2=new ArrayList<>();
for(int i=0;i<chars.length;i++){
if(i==0){
tmp1.add(new String(chars[i]+""));
}else{
for(int k=0;k<tmp1.size();k++){
String strTmp=tmp1.get(k);
String midStr=null;
for(int j=0;j<strTmp.length()+1;j++){
midStr=strTmp.substring(0,j)+chars[i]+strTmp.substring(j);
if(!tmp2.contains(midStr)){
tmp2.add(midStr);
}
}
}
tmp1=new ArrayList(tmp2);
tmp2.clear();
}
}
res=tmp1;
Collections.sort(res);
return res;
}
京公网安备 11010502036488号