这道题也很难,主要借鉴了博主的文章https://blog.csdn.net/zjxxyz123/article/details/79709240,博主文章中的图片,我觉得很好的解释了这道题的思路
回溯和递归可以很好的解决问题,主要注意在去重复,只要每层的字符不一样,就不会有重复,所以在每层前加一个HashSet防止重复即可。代码如下
import java.util.ArrayList;
import java.util.HashSet;
public class Solution {
ArrayList<String> as=new ArrayList<String>();
public ArrayList<String> Permutation(String str) {
if(str.length()==0||str==null)
return as;
p(str.toCharArray(),0);
return as;
}
public void p(char[] c,int i){
HashSet<Character> h=new HashSet<Character>();
if(i==c.length){
as.add(String.valueOf(c));
}
else{
for(int j=i;j<c.length;j++){
if(!h.contains(c[j])){
h.add(c[j]);
char temp=c[i];
c[i]=c[j];
c[j]=temp;
p(c,i+1);
temp=c[i];
c[i]=c[j];
c[j]=temp;
}
}
}
}
}