输入一个字符串,打印出该字符串中字符的所有排列。
以任意顺序返回这个字符串数组,但里面不能有重复元素。
示例:
输入:s = "abc"
输出:["abc","acb","bac","bca","cab","cba"]
思路:递归加回溯,将字符串从首位字符固定到末位字符。将每次递归得到的字符串放进set里去重。
StringBuilder temp = new StringBuilder();
HashSet<String> res = new HashSet<>();
char[] ch;
boolean[] visited;
public String[] permutation(String s) {
this.ch = s.toCharArray();
this.visited = new boolean[s.length()];
if(s == null || s.length() <= 0){
return null;
}
//从首位字符开始
dfs(0);
return res.toArray(new String[res.size()]);
}
public void dfs(int index){
//所有字符都已固定
if(index == ch.length){
res.add(temp.toString());
return;
}
for (int i = 0; i < ch.length; i++) {
//该字符已使用
if(visited[i]){
continue;
}
temp.append(ch[i]);
visited[i] = true;
dfs(index+1);
//回溯 去掉末位字符
temp.deleteCharAt(temp.length() - 1);
//取消使用标识
visited[i] = false;
}
}
参考:https://leetcode-cn.com/problems/zi-fu-chuan-de-pai-lie-lcof