-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy path0047-permutations-ii.js
52 lines (44 loc) · 1.09 KB
/
0047-permutations-ii.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// 47. Permutations II
// Medium 33%
// Given a collection of numbers that might contain duplicates, return all
// possible unique permutations.
// For example,
// [1,1,2] have the following unique permutations:
// [
// [1,1,2],
// [1,2,1],
// [2,1,1]
// ]
/**
* @param {number[]} nums
* @return {number[][]}
*/
const permuteUnique = function(nums) {
nums.sort((a, b) => a - b)
const result = [], n = nums.length
function iter(array, used) {
if (array.length === n) result.push([...array])
else {
for (let i = 0; i < n; i++) {
if (!used[i] && !(!used[i - 1] && nums[i] === nums[i - 1])) {
array.push(nums[i])
used[i] = true
iter(array, used)
array.pop(nums[i])
used[i] = false
}
}
}
}
iter([], [])
return result
}
;[
[1,1,2],
].forEach(nums => {
console.log(permuteUnique(nums))
})
// Solution:
// 使用一个标记数组表示,某个位置的数是否使用过。
// 在每层中选择一个没有使用过的数,且该数在该层之前也没有使用过。
// Submission Result: Accepted