剑指 Offer 38. 字符串的排列
题目描述
输入一个字符串,打印出该字符串中字符的所有排列。
你可以以任意顺序返回这个字符串数组,但里面不能有重复元素。
示例
输入:s = "abc" 输出:["abc","acb","bac","bca","cab","cba"]
数据限制
1 <= s 的长度 <= 8
思路
由于数据强度较小,我们可以直接使用DFS搜索,求出每一种情况。由于字符串中可能有相同的字符,如果不加处理,可能出现重复,因此我们可以设置一个Set集合,这个集合保存当前以及存在的字符串,每次要添加新字符串前,都先进行一个判断。最后,将Set中的字符串输出即可
时间复杂度:O(s.length() ^ s.length())
空间复杂度:O(s.length() ^ s.length())
代码:
class Solution {
Set<String> set = new HashSet<>();
boolean[] h;
int len;
List<Integer> list = new ArrayList<>();
String s;
public String[] permutation(String s) {
this.s = s;
len = s.length();
h = new boolean[len];
Arrays.fill(h, true);
su(0);
int n = set.size();
String[] ans = new String[n];
int l = 0;
for (String i : set){
ans[l] = i;
l++;
}
return ans;
}
void su(int x){
if (x == len){
String st = "";
for (int i = 0; i < len; i++){
st = st + s.charAt(list.get(i));
}
if (!set.contains(st)){
set.add(st);
}
return ;
}
for (int i = 0; i < len; i++){
if (h[i]){
h[i] = false;
list.add(i);
su(x + 1);
list.remove(list.size() - 1);
h[i] = true;
}
}
}
}