剑指 Offer 38. 字符串的排列
题目链接:https://leetcode.cn/problems/zi-fu-chuan-de-pai-lie-lcof/
个人题解记录
1.回溯
回溯算法里挺经典的一道题,注意的是需要排序 额外判断,不然类似aab这种字符串会被加入2次
class Solution {
List<String> list = new ArrayList<>();
StringBuilder builder = new StringBuilder();
public String[] permutation(String s) {
List<Character> set = new ArrayList<>();
for (int i =0;i<s.length();i++){
set.add(s.charAt(i));
}
int n = set.size();
char[] num = new char[n];
int i = 0;
for (char c :set){
num[i++] = c;
}
Arrays.sort(num);
int[] flag = new int[n];
Arrays.fill(flag,0);
back(num,flag,0);
String[] s1 = new String[list.size()];
for (int j = 0;j< list.size();j++){
s1[j] = list.get(j);
}
return s1;
}
private void back(char[] num,int [] flag,int index){
if (index == num.length){
list.add(builder.toString());
}
for (int i = 0;i< num.length;i++){
if (flag[i]!=1){
flag[i] = 1;
builder.append(num[i]);
back(num,flag,index+1);
flag[i] = 0;
builder.deleteCharAt(builder.length()-1);
while (i< num.length-1&&num[i]==num[i+1]){
i++;
}
}
}
}
}
leetcode题解的写法:每次确定一个位置的字符,然后将该位置的原字符替换过去,这样可以节省我的思路里面的flag数组,同时也可以少遍历,然后利用hashset记录当前位置已经选过的字符,不再选,可以节省我思路里面的判断下一个位置和排序。
题解的链接:https://leetcode.cn/problems/zi-fu-chuan-de-pai-lie-lcof/solutions/178988/mian-shi-ti-38-zi-fu-chuan-de-pai-lie-hui-su-fa-by/
class Solution {
List<String> res = new LinkedList<>();
char[] c;
public String[] permutation(String s) {
c = s.toCharArray();
dfs(0);
return res.toArray(new String[res.size()]);
}
void dfs(int x) {
if(x == c.length - 1) {
res.add(String.valueOf(c)); // 添加排列方案
return;
}
HashSet<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); // 交换,将 c[i] 固定在第 x 位
dfs(x + 1); // 开启固定第 x + 1 位字符
swap(i, x); // 恢复交换
}
}
void swap(int a, int b) {
char tmp = c[a];
c[a] = c[b];
c[b] = tmp;
}
}