剑指 Offer 38. 字符串的排列
题目描述
输入一个字符串,打印出该字符串中字符的所有排列。
你可以以任意顺序返回这个字符串数组,但里面不能有重复元素。
解答
class Solution {
/**
通过当前字符和后方字符的不断交换得到所有的排列结果
*/
List<String> res = new ArrayList<>();
char[] cs;
public String[] permutation(String s) {
cs = s.toCharArray();
dfs(0);
return res.toArray(new String[res.size()]);
}
public void dfs(int x){
if(x == cs.length-1){
res.add(String.valueOf(cs));
return;
}
Set<Character> s = new HashSet<>();
for(int i = x;i < cs.length;i++){
if(s.contains(cs[i])){
continue;
}
s.add(cs[i]);
swap(i,x);
dfs(x+1);
swap(i,x);
}
}
public void swap(int x,int y){
char temp = cs[x];
cs[x] = cs[y];
cs[y] = temp;
}
}