题目要求不能出现重复的结果,可以考虑全排列之后去重,但会有大量重复计算。所以可以在回溯过程中,添加特殊情况的判断。我们可以先把所有可用字符进行排序,保证重复字符在相邻的位置上,然后在选取下一个字符的过程中,跳过哪些重复的。
const permutation = (s) => {
const len = s.length;
const res = [];
const chars = s.split('').sort();
const tmp = [];
const visited = Array(len).fill(false);
const dfs = (i) => {
// all the characters are used
if (i >= len) {
res.push(tmp.join(''));
return;
}
chars.forEach((char, index) => {
if (visited[index]) {
// skip all the characters are used before
return;
}
if (index > 0 && !visited[index - 1] && char === chars[index - 1]) {
// skip all the same characters
return;
}
visited[index] = true;
tmp.push(char);
dfs(i + 1);
tmp.pop();
visited[index] = false;
});
}
dfs(0);
return res;
};