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], [] ]
Solution(javascript)
// 1: recursion
// const subsets = (nums = []) => {
// const result = []
// const aux = (index, current) => {
// if (index === nums.length) {
// result.push(current)
// }
// if (index < nums.length) {
// aux(index + 1, current)
// aux(index + 1, [...current, nums[index]])
// }
// }
// aux(0, [])
// return result
// }
// 2: Bit Manipulation
const subsets = (nums = []) => {
const result = []
const { length } = nums
for (let i = 0; i < 2 ** length; i++) {
const current = []
for (let j = 0; j < length; j++) {
if (i & (1 << j)) {
current.push(nums[j])
}
}
result.push(current)
}
return result
}