Skip to content

Commit 37ccfb4

Browse files
committed
Add subsets II LC medium JS solution
1 parent 8bf3d6c commit 37ccfb4

File tree

3 files changed

+90
-0
lines changed

3 files changed

+90
-0
lines changed

src/leetcode/medium/medium.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@
7070
- [Sort Colors](#sort-colors)
7171
- [Spiral Matrix](spiral-matrix)
7272
- [Subsets](subsets)
73+
- [Subsets II](subsets-ii)
7374
- [Target Sum](target-sum)
7475
- [Time-Based Key Value Store](time-based-key-value-store)
7576
- [Top K Frequent ELements](top-k-frequent-elements)
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/*
2+
https://leetcode.com/problems/subsets-ii/description
3+
4+
Given an integer array nums that may contain duplicates, return all possible subsets (the power set).
5+
6+
The solution set must not contain duplicate subsets. Return the solution in any order.
7+
8+
Example 1:
9+
Input: nums = [1,2,2]
10+
Output: [[],[1],[1,2],[1,2,2],[2],[2,2]]
11+
12+
Example 2:
13+
Input: nums = [0]
14+
Output: [[],[0]]
15+
16+
Constraints:
17+
1 <= nums.length <= 10
18+
-10 <= nums[i] <= 10
19+
*/
20+
21+
const subsetsWithDup = (nums) => {
22+
nums.sort((a, b) => a - b);
23+
24+
function backtrack(step = 0, subset = []) {
25+
if (step >= nums.length) {
26+
return [subset];
27+
}
28+
29+
const result = [subset];
30+
let prev = -Infinity;
31+
for (let i = step; i < nums.length; i++) {
32+
const currentNum = nums[i];
33+
34+
if (currentNum !== prev) {
35+
prev = currentNum;
36+
result.push(...backtrack(i + 1, [...subset, currentNum]));
37+
}
38+
}
39+
40+
return result;
41+
}
42+
43+
return backtrack();
44+
};
45+
46+
module.exports = { subsetsWithDup };
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
const { subsetsWithDup } = require("./subsetsII");
2+
3+
describe("subsetsWithDup", () => {
4+
it("returns all possible subsets for a short array of nums", () => {
5+
const result = subsetsWithDup([1, 2, 2]);
6+
expect(result).toEqual([[], [1], [1, 2], [1, 2, 2], [2], [2, 2]]);
7+
});
8+
9+
it("returns all possible subsets for a long array of nums", () => {
10+
const result = subsetsWithDup([1, 2, 2, 3, 3, 3]);
11+
expect(result).toEqual([
12+
[],
13+
[1],
14+
[1, 2],
15+
[1, 2, 2],
16+
[1, 2, 2, 3],
17+
[1, 2, 2, 3, 3],
18+
[1, 2, 2, 3, 3, 3],
19+
[1, 2, 3],
20+
[1, 2, 3, 3],
21+
[1, 2, 3, 3, 3],
22+
[1, 3],
23+
[1, 3, 3],
24+
[1, 3, 3, 3],
25+
[2],
26+
[2, 2],
27+
[2, 2, 3],
28+
[2, 2, 3, 3],
29+
[2, 2, 3, 3, 3],
30+
[2, 3],
31+
[2, 3, 3],
32+
[2, 3, 3, 3],
33+
[3],
34+
[3, 3],
35+
[3, 3, 3],
36+
]);
37+
});
38+
39+
it("returns all possible subsets for an array of same nums", () => {
40+
const result = subsetsWithDup([7, 7]);
41+
expect(result).toEqual([[], [7], [7, 7]]);
42+
});
43+
});

0 commit comments

Comments
 (0)