-
Notifications
You must be signed in to change notification settings - Fork 20
/
SubsetsII.js
114 lines (96 loc) · 2.43 KB
/
SubsetsII.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
/**
* Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).
*
* Note: The solution set must not contain duplicate subsets.
*
* For example,
* If nums = [1,2,2], a solution is:
*
* [
* [2],
* [1],
* [1,2,2],
* [2,2],
* [1,2],
* []
* ]
*
* Accepted.
*/
/**
* @param {number[]} nums
* @return {number[][]}
*/
let subsetsWithDup = function (nums) {
if (nums === null || nums.length === 0) {
return [];
}
let lists = [];
if (nums.length === 1) {
lists.push([], [nums[0]]);
return lists;
}
nums.sort();
subsetsWithDup(nums.slice(0, nums.length - 1)).forEach(function (list) {
let l = [];
l.push(nums[nums.length - 1]);
list.forEach(function (i) {
l.push(i);
});
let equalsL = false;
let equalsList = false;
for (let i = 0; i < lists.length; i++) {
if (lists[i].toString() === list.toString()) {
equalsList = true;
}
if (lists[i].toString() === l.toString()) {
equalsL = true;
}
if (equalsList && equalsL) {
break;
}
}
if (!equalsList) {
lists.push(list);
}
if (!equalsL) {
lists.push(l);
}
});
return lists;
};
if (subsetsWithDup(null).length === 0) {
console.log("pass")
} else {
console.error("failed")
}
if (subsetsWithDup([]).length === 0) {
console.log("pass")
} else {
console.error("failed")
}
if (subsetsWithDup([1]).toString() === [[], [1]].toString()) {
console.log("pass")
} else {
console.error("failed")
}
if (new Set(subsetsWithDup([1, 1])).toString() === new Set([[], [1], [1, 1]]).toString()) {
console.log("pass")
} else {
console.error("failed")
}
if (new Set(subsetsWithDup([1, 2])).toString() === new Set([[], [1], [2], [1, 2]]).toString()) {
console.log("pass")
} else {
console.error("failed")
}
if (new Set(subsetsWithDup([1, 2, 2])).toString() === new Set([[], [1], [2], [1, 2], [2, 2], [1, 2, 2]]).toString()) {
console.log("pass")
} else {
console.error("failed")
}
if (new Set(subsetsWithDup([4, 4, 4, 1, 4])).toString() === new Set([[], [1], [4], [1, 4], [1, 4, 4], [1, 4, 4, 4], [1, 4, 4, 4, 4], [4, 4], [4, 4, 4], [4, 4, 4, 4]]).toString()) {
console.log("pass")
} else {
console.error("failed")
}