1. 题目
2. 思路
(1) 回溯+HashSet
- 利用回溯遍历全排列的结果,利用HashSet去重。
3. 代码
import java.util.ArrayList;
import java.util.HashSet;
public class Test {
public static void main(String[] args) {
}
}
class Solution {
public ArrayList<String> Permutation(String str) {
char[] chars = str.toCharArray();
int n = chars.length;
HashSet<String> res = new HashSet<>();
backtrack(chars, 0, n, res);
return new ArrayList<>(res);
}
public void backtrack(char[] chars, int index, int n, HashSet<String> res) {
if (index == n) {
res.add(new String(chars));
return;
}
for (int i = index; i < n; i++) {
if (i < n - 1 && chars[i] == chars[i + 1]) {
continue;
}
char temp = chars[index];
chars[index] = chars[i];
chars[i] = temp;
backtrack(chars, index + 1, n, res);
temp = chars[index];
chars[index] = chars[i];
chars[i] = temp;
}
}
}