给定一个可包含重复数字的序列,返回所有不重复的全排列。
示例:
输入: [1,1,2] 输出: [ [1,1,2], [1,2,1], [2,1,1] ]
/**
* 排序后,用一个数组记录每一个元素的使用情况,
* 遇到连续重复的两个数字,且前一个数字是被使用过被回退出来的时候,
* 直接跳过这个数字进入下一个数字决策
* @param {number[]} nums
* @return {number[][]}
*/
var permuteUnique = function(nums) {
nums = nums.sort((a, b) => a - b);
let results = []
hash = [];
let backtrack = (results, tempList, nums) => {
if(tempList.length == nums.length){
return results.push([...tempList]);
}
for(let i = 0; i < nums.length; i++){
if(hash[i] || (i > 0 && nums[i] == nums[i-1] && !hash[i-1])){
continue;
}
hash[i] = true;
tempList.push(nums[i]);
backtrack(results, tempList, nums);
tempList.pop();
hash[i] = false;
}
}
backtrack(results, [], nums);
return results;
};
← 全排列(回溯算法) 删除排序数组中的重复项 →