The problem. Given an array nums of distinct integers, return all possible subsets (the power set). The answer must not contain duplicate subsets, in any order.
nums = [1, 2, 3] -> [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
nums = [0] -> [[], [0]]Every problem in this chapter chooses some items where order doesn't matter: all subsets, subsets without duplicates, k numbers out of n, numbers that add up to a target, letters for each digit. The decision tree either asks take or skip? for each item, or loops over the items from a start index onwards so the same group is never built in two orders. Pruning — stopping when the sum is already too big, or too few items are left — keeps the tree small.
Start with just the empty subset. For each number, copy every subset you have so far and add the number to the copy. Each number doubles the list.
function subsets(nums) { let result = [[]]; for (const x of nums) { result = [...result, ...result.map((s) => [...s, x])]; // every subset, with and without x } return result;}Time O(n · 2ⁿ), space O(n · 2ⁿ) — that's the size of the answer itself.
Each level decides one number: take it, explore, untake it, then explore without it.
function subsets(nums) { const result = []; const path = []; const decide = (i) => { if (i === nums.length) { // every number decided: one subset result.push([...path]); return; } path.push(nums[i]); // take nums[i] decide(i + 1); path.pop(); // un-take it ... decide(i + 1); // ... and skip it }; decide(0); return result;}Time O(n · 2ⁿ): 2ⁿ leaves, each copied in O(n). Space O(n) for the path and the call stack, besides the output.
Number the subsets 0 to 2ⁿ − 1. In binary, bit j of the number says whether nums[j] is in that subset — the decision tree flattened into counting.
function subsets(nums) { const result = []; for (let mask = 0; mask < 1 << nums.length; mask++) { result.push(nums.filter((_, j) => mask & (1 << j))); // bit j on: nums[j] is in } return result;}Time O(n · 2ⁿ), space O(1) besides the output. Neat for n up to about 20.
[[], [x]].