首先将字符串变为字符数组并排序
使用递归,在每次递归中,遍历字符数组中没有做标记的元素,加到字符串中,并将字符数组的元素做标记,递归,并在递归结束时,撤销标记,并删除字符串最后一个元素;
注:考虑字符数组中有相同元素
当字符数组所有元素均做了标记以后就将字符串加入字符串数组
class Solution {
List<String> str_s;
char[] new_s;
StringBuilder res;
public String[] permutation(String s) {
if(s.length() == 0) return new String[0];
str_s = new ArrayList<>();
new_s = s.toCharArray();
res = new StringBuilder("");
Arrays.sort(new_s);
List<Integer> lists = new ArrayList<>();
for(int i = 0; i < new_s.length; i++)
lists.add(i);
dfs(lists);
String[] ss = new String[str_s.size()];
for(int i =0; i < str_s.size(); i++){
ss[i] = str_s.get(i);
}
return ss;
}
private void dfs(List<Integer> lists){
if(lists.size() == 0){
str_s.add(res.toString());
}
for(int i = 0; i < lists.size(); i++){
if(i == 0 || new_s[lists.get(i)] != new_s[lists.get(i - 1)]){
int item = lists.get(i);
res.append(new_s[lists.get(i)]);
lists.remove(i);
dfs(lists);
lists.add(i, item);
res.deleteCharAt(res.length() - 1);
}
}
}
}