Appearance
47. 全排列 II
给定一个可包含重复数字的序列 nums ,按任意顺序 返回所有不重复的全排列
示例 1:
输入:nums = [1,1,2]
输出:
[[1,1,2],
[1,2,1],
[2,1,1]]
示例 2:
输入:nums = [1,2,3]
输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
提示:
1 <= nums.length <= 8
-10 <= nums[i] <= 10
- 来源:力扣(LeetCode)
- 链接:https://leetcode.cn/problems/permutations-ii
javascript
/**
* @param {number[]} nums
* @return {number[][]}
*/
var permuteUnique = function (nums) {
const res = []
const vis = Array.from({ length: nums.length }, () => false)
const backtrack = (idx, perm) => {
if (idx === nums.length) {
res.push(perm.slice())
return
}
for (let i = 0; i < nums.length; ++i) {
if (vis[i] || (i > 0 && nums[i] === nums[i - 1] && !vis[i - 1])) {
continue
}
perm.push(nums[i])
vis[i] = true
backtrack(idx + 1, perm)
vis[i] = false
perm.pop()
}
}
nums.sort((a, b) => a - b)
backtrack(0, [])
return res
}
console.log(permuteUnique([1, 1, 2]))
console.log(permuteUnique([1, 2, 3]))