-
Notifications
You must be signed in to change notification settings - Fork 20
/
Subsets.js
82 lines (70 loc) · 1.51 KB
/
Subsets.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
/**
* Given a set of distinct integers, nums, return all possible subsets (the power set).
*
* Note: The solution set must not contain duplicate subsets.
*
* For example,
* If nums = [1,2,3], a solution is:
*
* [
* [3],
* [1],
* [2],
* [1,2,3],
* [1,3],
* [2,3],
* [1,2],
* []
* ]
*
* Accepted.
*/
/**
* @param {number[]} nums
* @return {number[][]}
*/
let subsets = function (nums) {
let results = [];
results.push([]);
if (nums == null || nums.length === 0) {
return results;
}
nums.sort();
nums.forEach(function (i) {
let size = results.length;
for (let j = 0; j < size; j++) {
let list = [];
results[j].forEach(function (element) {
list.push(element);
});
list.push(i);
results.push(list);
}
});
return results;
};
if (subsets([]).toString() === [[]].toString()) {
console.log("pass")
} else {
console.error("failed")
}
if (subsets(null).toString() === [[]].toString()) {
console.log("pass")
} else {
console.error("failed")
}
if (subsets([1]).toString() === [[], [1]].toString()) {
console.log("pass")
} else {
console.error("failed")
}
if (subsets([1, 2]).toString() === [[], [1], [2], [1, 2]].toString()) {
console.log("pass")
} else {
console.error("failed")
}
if (subsets([1, 2, 3]).toString() === [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]].toString()) {
console.log("pass")
} else {
console.error("failed")
}