Last active
April 9, 2020 17:45
-
-
Save iankit3/afa1ae4a94d22b6f7389e34e1321bf9c to your computer and use it in GitHub Desktop.
LC-78, Subsets, PowerSet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// LC-78 | |
// https://leetcode.com/problems/subsets/ | |
// Unique subsets | |
(function() { | |
var subsets = function(nums) { | |
if (nums.length == 0) { | |
return [[]]; // empty | |
} | |
let first = nums.slice(0, 1), | |
rest = nums.slice(1); | |
let subs = subsets(rest), | |
out = []; | |
for (let i = 0; i < subs.length; ++i) { | |
out.push(subs[i]); | |
out.push(subs[i].concat(first)); | |
} | |
return out; | |
}; | |
console.log(JSON.stringify(subsets([1,2,3,4]))); | |
})(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function() { | |
var subsets = function(subs, nums) { | |
if (nums.length == 0) { | |
return subs; | |
} | |
//console.log(subs) | |
return subsets(subs, nums.slice(1)) | |
.concat("|") | |
.concat(subsets([...subs, nums[0]], nums.slice(1))); | |
}; | |
console.log( | |
subsets([], [1, 2, 3, 4]) | |
.join(",") | |
.split("|") | |
); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment