-
Notifications
You must be signed in to change notification settings - Fork 154
/
permutations-ii.js
45 lines (40 loc) · 926 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
37
38
39
40
41
42
43
44
45
/**
* Permutations II
*
* 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 = nums => {
const results = [];
nums.sort((a, b) => a - b);
backtracking(nums, {}, [], results);
return results;
};
const backtracking = (nums, used, solution, results) => {
if (solution.length === nums.length) {
results.push(solution.slice());
return;
}
for (let i = 0; i < nums.length; i++) {
if (used[i] || (i > 0 && nums[i] === nums[i - 1] && !used[i - 1])) {
continue;
}
solution.push(nums[i]);
used[i] = true;
backtracking(nums, used, solution, results);
solution.pop();
used[i] = false;
}
};
export default permuteUnique;