Subsets
Difficulty: Medium · Pattern: Backtracking · LeetCode #78
Given an array of distinct integers, return every possible subset (the power set), including the empty set. Subsets may be returned in any order, with no duplicates.
Examples
text
nums = [1, 2, 3] → [[], [1], [2], [3], [1,2], [1,3], [2,3], [1,2,3]]
nums = [0] → [[], [0]]Hints
- There are 2ⁿ subsets: each element is either included or not.
- Backtracking: at each call, record the current subset, then try adding each element after
start. - Iterative: start with
[[]]; for each number, add it to every existing subset.
Approach
Backtracking with a start index: every node of the recursion tree is a valid subset, so record a copy on entry. Then for i from start to n − 1, append nums[i], recurse with start = i + 1, and pop. The start index ensures each combination is generated once, in increasing index order.
Complexity
Time: O(n · 2ⁿ), with 2ⁿ subsets copied at O(n) each. Space: O(n) recursion (excluding output).
Python solution
def subsets(nums):
res, path = [], []
def bt(start):
res.append(path[:])
for i in range(start, len(nums)):
path.append(nums[i])
bt(i + 1)
path.pop()
bt(0)
return resJavaScript solution
function subsets(nums) {
const res = [], path = [];
const bt = (start) => {
res.push([...path]);
for (let i = start; i < nums.length; i++) {
path.push(nums[i]);
bt(i + 1);
path.pop();
}
};
bt(0);
return res;
}