forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPermutations II.js
36 lines (27 loc) · 833 Bytes
/
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
// Runtime: 122 ms (Top 61.38%) | Memory: 44.5 MB (Top 89.57%)
var permuteUnique = function(nums) {
const answer = []
function perm (pos, array) {
if (pos >= array.length) {
answer.push(array)
}
const setObject = new Set()
for (let index=pos; index<array.length; index++) {
if (setObject.has(array[index])) {
continue
}
setObject.add(array[index])
// swap numbers
let temp = array[pos]
array[pos] = array[index]
array[index] = temp
perm(pos + 1, [...array])
// undo swapping for next iteration
temp = array[index]
array[index] = array[pos]
array[pos] = temp
}
}
perm(0, nums)
return answer
};