Subsets
Difficulty: Medium
Given a list of distinct numbers, return every possible subset - including the empty subset and the full list.
The order of numbers within a subset, and the order of subsets, don't matter.
Examples
Input: nums = [1, 2, 3]
Output: [[], [1], [2], [1,2], [3], [1,3], [2,3], [1,2,3]]
There are 2^3 = 8 ways to include or exclude each of the three numbers.
Input: nums = [0]
Output: [[], [0]]
A single number has exactly two subsets: empty, and itself.
Constraints
1 <= nums.length <= 10
-10 <= nums[i] <= 10
All numbers in nums are unique.
Approach
Each number is either included or excluded, so try both for every number.
The brute-force way lists all 2^n combinations of in/out decisions (one per number). Each combination describes exactly one subset.
A more natural way builds one subset at a time. Include a number and move on to the next. After exploring every path that starts with "included", undo that choice and explore every path with "excluded". Trying a choice, exploring what follows, then undoing it is the core of backtracking - and it visits every subset exactly once.
Solutions
Brute Force — Bitmask Enumeration
Each subset is a sequence of n include/exclude decisions - exactly what an n-bit binary number represents. Loop through every integer from 0 to 2^n - 1: if bit i is 1, include nums[i].
function subsets(nums) {
const n = nums.length;
const result = [];
for (let mask = 0; mask < (1 << n); mask++) {
const subset = [];
for (let i = 0; i < n; i++) {
if (mask & (1 << i)) {
subset.push(nums[i]);
}
}
result.push(subset);
}
return result;
}Time: O(2^n * n) · Space: O(2^n * n)
Optimal — Backtracking (Choose / Explore / Un-choose)
Build one subset at a time in a running list. At each number, first include it (push, recurse, pop), then skip it (just recurse). When you reach the end of the list, the subset is complete - save a copy.
function subsets(nums) {
const result = [];
const current = [];
function backtrack(index) {
if (index === nums.length) {
result.push([...current]);
return;
}
// Choice 1: include nums[index]
current.push(nums[index]);
backtrack(index + 1);
current.pop(); // undo the choice
// Choice 2: skip nums[index]
backtrack(index + 1);
}
backtrack(0);
return result;
}Time: O(2^n * n) · Space: O(n) auxiliary (recursion depth), plus O(2^n * n) for the output