forked from ignacio-chiazzo/Algorithms-Leetcode-Javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSubsets.js
39 lines (32 loc) · 759 Bytes
/
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
/*
Subsets
https://leetcode.com/problems/subsets/description/
Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
Example:
Input: nums = [1,2,3]
Output:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
*/
var subsets = function (nums) {
var subsetByPosition = function (nums, position, current) {
if (position == nums.length) {
return [current];
}
var currentRight = current.slice().concat([nums[position]]);
return subsetByPosition(nums, position + 1, currentRight).concat(
subsetByPosition(nums, position + 1, current)
);
};
return subsetByPosition(nums, 0, []);
};
module.exports.subsets = subsets;