Subsets (LeetCode 78): Solution and Explanation
Given an array of distinct integers, return every possible subset, including the empty set and the full array. No subset may appear twice, and the order of the output does not matter.
Watch it run step by step
Try your own input and write the code →Intuition
Every subset can be described by a yes or no decision for each element: is nums[0] in it, is nums[1] in it, and so on. With n elements that is n independent binary choices, so there are exactly 2^n subsets. Any correct solution has to produce all of them, and each can be up to n elements long, so O(n × 2^n) is the best possible.
Those binary decisions form a decision tree. At depth i you decide about nums[i], branching once to include it and once to exclude it. After n decisions you reach a leaf, and the elements you said yes to form one subset. A depth-first walk of this tree visits every leaf exactly once, so it generates every subset with no duplicates and no need for a seen set.
Backtracking lets you walk the tree with a single shared list. Append nums[i] and recurse to explore the include branch, then pop it and recurse again to explore the exclude branch. The pop restores the list to exactly what it was before the decision, so the two branches do not interfere with each other. At each leaf you save a copy, since the shared list will keep changing.
Approach: Include or exclude backtracking
- Create
resfor the results and a shared listsubsetfor the current choices. - Define
dfs(i). Ifi >= len(nums), every element has been decided, so append a copy ofsubsettoresand return. - Include branch: append
nums[i]tosubsetand calldfs(i + 1). - Exclude branch: pop
nums[i]fromsubsetand calldfs(i + 1)again. - Call
dfs(0)and returnres.
Step-by-step example
nums = [1,2,3]
- Include 1, include 2, include 3, then reach the end: record [1,2,3].
- Back at index 2, pop 3 and take the exclude branch: record [1,2].
- Back at index 1, pop 2. Now
subset = [1]; include 3 to record [1,3], then exclude it to record [1]. - Back at index 0, pop 1. With
subset = [], the same pattern records [2,3], [2], [3] and finally []. - The result holds 8 = 2^3 subsets: [1,2,3], [1,2], [1,3], [1], [2,3], [2], [3], [].
Code: Python, Java, C++
1class Solution:
2 def subsets(self, nums: List[int]) -> List[List[int]]:
3 res = []
4 subset = []
5
6 def dfs(i):
7 if i >= len(nums):
8 res.append(subset.copy())
9 return
10
11 # include nums[i]
12 subset.append(nums[i])
13 dfs(i + 1)
14
15 # exclude nums[i]
16 subset.pop()
17 dfs(i + 1)
18
19 dfs(0)
20 return res1class Solution {
2 public List<List<Integer>> subsets(int[] nums) {
3 List<List<Integer>> res = new ArrayList<>();
4 List<Integer> subset = new ArrayList<>();
5 dfs(0, nums, subset, res);
6 return res;
7 }
8
9 private void dfs(int i, int[] nums, List<Integer> subset, List<List<Integer>> res) {
10 if (i >= nums.length) {
11 res.add(new ArrayList<>(subset));
12 return;
13 }
14
15 subset.add(nums[i]);
16 dfs(i + 1, nums, subset, res);
17
18 subset.remove(subset.size() - 1);
19 dfs(i + 1, nums, subset, res);
20 }
21}1class Solution {
2public:
3 vector<vector<int>> subsets(vector<int>& nums) {
4 vector<vector<int>> res;
5 vector<int> subset;
6 dfs(0, nums, subset, res);
7 return res;
8 }
9
10 void dfs(int i, vector<int>& nums, vector<int>& subset, vector<vector<int>>& res) {
11 if (i >= nums.size()) {
12 res.push_back(subset);
13 return;
14 }
15
16 subset.push_back(nums[i]);
17 dfs(i + 1, nums, subset, res);
18
19 subset.pop_back();
20 dfs(i + 1, nums, subset, res);
21 }
22};Time and space complexity
O(n × 2^n)
The decision tree has 2^n leaves, and at each leaf the code copies a list of up to n elements. Internal nodes do constant work, so copying dominates.
O(n)
Excluding the output, the recursion is n levels deep and subset holds at most n values. The output itself takes O(n × 2^n). For the largest input of 10 elements that is 1,024 lists.
Other approaches
Iterative cascading (time O(n × 2^n), space O(n × 2^n))
Start with [[]]. For each number, take every subset already in the result, copy it with the number appended, and add the copies. After all numbers the list holds every subset. It is short and avoids recursion.
Bitmask enumeration (time O(n × 2^n), space O(n))
Loop a mask from 0 to 2^n - 1 and include nums[j] whenever bit j of the mask is set. Each mask maps to one subset. It is very direct and works well when n is small, as it is here.
Common mistakes
- Appending
subsetinstead ofsubset.copy(), so every result is the same list that ends up empty. - Forgetting the pop before the exclude branch, which carries
nums[i]into subsets that were supposed to skip it. - Recording subsets only when they are non-empty, which drops the empty set that the problem requires.
- Applying this code to input with duplicates, which produces repeated subsets. That variant needs sorting and skipping equal neighbors.
Frequently asked questions
How many subsets does an array of n elements have?
Exactly 2^n, because each element is independently either in or out of a subset. For n = 10, the largest input here, that is 1,024 subsets.
What is the time complexity of generating subsets?
It is O(n × 2^n). There are 2^n subsets and building or copying each one can take up to n steps, which is also the size of the output.
Backtracking or bitmask for subsets?
Both have the same complexity. Bitmasks are compact for small n, while backtracking generalizes better to variants with duplicates or constraints, such as combination sums, where you want to prune branches early.
How do you handle duplicate elements?
Sort the array first. When you decide to exclude a value, skip past all copies of it before recursing, so the same subset is never generated through two different branches.