剑指 Offer 38. 字符串的排列
题目:
输入一个字符串,打印出该字符串中字符的所有排列。
你可以以任意顺序返回这个字符串数组,但里面不能有重复元素。
示例:
输入:s = "abc"
输出:["abc","acb","bac","bca","cab","cba"]
限制:
1 <= s 的长度 <= 8
题解
DFS深度优先搜索,注意结果集不能有重复元素,需要用一个HashSet来存储。
Code
class Solution {
StringBuilder sb = new StringBuilder();
HashSet<String> set = new HashSet<>();
int count = 0;
public String[] permutation(String s) {
if(s == null){
return null;
}
boolean[] st = new boolean[s.length()];
dfs(s, st);
return set.toArray(new String[0]);
}
public void dfs(String s, boolean[] st){
if(count == s.length()){
set.add(sb.toString());
return;
}
for(int i = 0; i <s.length(); i++){
if(!st[i]){
st[i] = true;
sb.append(s.charAt(i));
count ++;
dfs(s, st);
sb.deleteCharAt(sb.length() - 1);
st[i] = false;
count --;
}
}
}
}