-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0090-subsets-ii.js
64 lines (49 loc) · 1.38 KB
/
0090-subsets-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
53
54
55
56
57
58
59
60
61
62
63
64
/**
* https://leetcode.com/problems/subsets-ii/
* Time O(N * 2^N) | Space O(N)
* @param {number[]} nums
* @return {number[][]}
*/
var subsetsWithDup = function(nums) {
nums.sort((a, b) => a - b);
return dfs(nums);
};
const dfs = (nums, index = 0, set = [], subset = []) => {
subset.push(set.slice())
for (let i = index; i < nums.length; i++) {
const isDuplicate = (index < i) && (nums[i - 1] === nums[i])
if (isDuplicate) continue;
backTrack(nums, i, set, subset);
}
return subset
}
const backTrack = (nums, i, set, subset) => {
set.push(nums[i]);
dfs(nums, (i + 1), set, subset);
set.pop();
}
/**
* https://leetcode.com/problems/subsets-ii/
* Time O(N * 2^N) | Space O(N * 2^N)
* @param {number[]} nums
* @return {number[][]}
*/
var subsetsWithDup = (nums) => {
nums.sort((a, b) => a - b);
return bfs(nums)
}
const bfs = (nums, subsets = [[]]) => {
let levels = subsets.length - 1
for (let i = 0; i < nums.length; i++) {
const isPrevDuplicate = (0 < i) && (nums[i - 1] === nums[i])
const start = isPrevDuplicate
? (levels + 1)
: 0
levels = subsets.length - 1
for (let level = start; level < (levels + 1); level++) {
const nextLevel = [ ...subsets[level], nums[i] ]
subsets.push(nextLevel)
}
}
return subsets
}