-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0078-subsets.js
53 lines (42 loc) · 1.09 KB
/
0078-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
/**
* https://leetcode.com/problems/subsets/
* Time O(N * 2^N) | Space(N)
* @param {number[]} nums
* @return {number[][]}
*/
var subsets = (nums) => {
nums.sort((a, b) => a -b);
return dfs(nums)
}
var dfs = (nums, level = 0, set = [], subset = []) => {
subset.push(set.slice());
for (let i = level; i < nums.length; i++){
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/
* Time O(N * 2^N) | Space(N * 2^N)
* @param {number[]} nums
* @return {number[][]}
*/
var subsets = (nums) => {
nums.sort((a, b) => a -b);
return bfs(nums)
}
const bfs = (nums, subsets = [[]]) => {
for (const num of nums) {
const levels = subsets.length
for (let level = 0; level < levels; level++) {
const nextLevel = [ ...subsets[level], num ]
subsets.push(nextLevel)
}
}
return subsets
}