给定一个可包含重复数字的序列 nums ,按任意顺序 返回所有不重复的全排列。
var permuteUnique = function (nums) {
const res = [],
set = new Set(),
visited = new Array(nums.length).fill(0);
const recursion = (nums, arr = [], visited = [], set = []) => {
if (arr.length === nums.length) {
res.push(arr.slice());
return;
}
for (let i = 0; i < nums.length; i++) {
if (visited[i]) continue;
visited[i] = true;
arr.push(nums[i]);
if (set.has(arr.join(''))) {
arr.pop();
visited[i] = false;
continue;
}
set.add(arr.join(''));
recursion(nums, arr, visited, set);
arr.pop();
visited[i] = false;
}
};
recursion(nums, [], visited, set);
return res;
};
// 测试
console.log(permuteUnique([1, 1, 2])); // [ [ 1, 1, 2 ], [ 1, 2, 1 ], [ 2, 1, 1 ] ]
console.log(permuteUnique([1, 2, 3])); // [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]