题目描述:
输入一个字符串,打印出该字符串中字符的所有排列。
你可以以任意顺序返回这个字符串数组,但里面不能有重复元素。
示例:
输入:s = “abc”
输出:[“abc”,“acb”,“bac”,“bca”,“cab”,“cba”]
题目分析:
参考代码:
private char[] c;
private List<String> res;
public String[] permutation(String s) {
if(s == null || s.length() == 0)return new String[]{};
res = new LinkedList<>();
c = s.toCharArray();
dfs(0);
return res.toArray(new String[res.size()]);//将字符串列表List<String>转换为string[]数组
}
public void dfs(int x){
if(x == c.length - 1){
res.add(String.valueOf(c));
return;
}
Set<Character> set = new HashSet<>();
for(int i = x; i < c.length; i++){
if(set.contains(c[i]))continue;
set.add(c[i]);
swap(i, x);
dfs(x + 1);
swap(i, x);
}
}
public void swap(int i, int j){
char t = c[i];
c[i] = c[j];
c[j] = t;
}