Subsets
Medium
Topics
Given an array nums of unique integers, return all possible subsets (the power set). The result may be in any order; this judge compares them order-independently.
Example 1
Each chip is one subset. Every element is independently in or out, which is why the empty set and the whole array both count, and why there are exactly 8 of them. The input holds no duplicates, so no two subsets come out equal.
Each chip is one subset.
Input: nums = [1,2,3] Output: [[],[1],[2],[3],[1,2],[1,3],[2,3],[1,2,3]]
Example 2
Input: nums = [0] Output: [[],[0]]
Constraints
- 1 <= nums.length <= 10
- All numbers are unique.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Each element is either in a subset or not — that binary choice over n elements generates all 2^n subsets. Backtracking explores the include/exclude tree.
Approach
- DFS carrying the current index and partial subset.
- At each index, record the current subset, then try adding each later element.
- Alternatively enumerate bitmasks 0..2^n-1.
Dry Run
nums = [1, 2, 3]
Every node of the recursion tree IS a subset -- there is no "is it complete?"
test, because the path is emitted on arrival:
emit [] loop i from 0
emit [1] loop i from 1
emit [1, 2] loop i from 2
emit [1, 2, 3] loop i from 3, nothing left
emit [1, 3] loop i from 3
emit [2] loop i from 2
emit [2, 3] loop i from 3
emit [3] loop i from 3
answer [] | [1] | [1,2] | [1,2,3] | [1,3] | [2] | [2,3] | [3]
`start` is what prevents duplicates without any sorting or set. Element i may
only be followed by elements after it, so each subset is generated in exactly one
order -- [1,3] is reachable but [3,1] is not. Recurse from i instead of i + 1 and
an element can follow itself, so the search never terminates: RecursionError.
Moving the emit below the loop does NOT empty the output, which is worth knowing
if you are told it does. `path.pop()` runs after each recursive call returns, so
path still holds the current subset when the function ends. All eight subsets
still appear, in post-order instead of pre-order:
[1,2,3] [1,2] [1,3] [1] [2,3] [2] [3] []. The set is identical and only the
ORDER changes -- which is still a failure against a judge that fixes the order,
just not for the reason you might expect.Complexity
- Time — O(n * 2^n): there are 2^n subsets, each copied in O(n).
- Space — O(n): recursion depth (excluding output).
Common Pitfalls
- Record the path before the loop, not after — but not because moving it below empties the output, which it does not.
path.pop()runs after each recursive call returns, sopathstill holds the current subset when the function ends, and all eight subsets are still emitted, in post-order:[1,2,3] [1,2] [1,3] [1] [2,3] [2] [3] []. The set is identical and only the order changes, which still fails a judge that fixes the order. - Recurse from
i + 1. Passingiallows an element to be reused, so the search never terminates and dies withRecursionError.
Full Solution — all languages
class Solution:
def subsets(self, nums):
res=[]
def dfs(start,path):
res.append(path[:])
for i in range(start,len(nums)):
path.append(nums[i]); dfs(i+1,path); path.pop()
dfs(0,[])
return resimport java.util.*;
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res=new ArrayList<>();
dfs(nums,0,new ArrayList<>(),res);
return res;
}
void dfs(int[] nums,int start,List<Integer> path,List<List<Integer>> res) {
res.add(new ArrayList<>(path));
for(int i=start;i<nums.length;i++) {
path.add(nums[i]);
dfs(nums,i+1,path,res);
path.remove(path.size()-1);
}
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> res;
vector<int> path;
function<void(int)> dfs=[&](int start) {
res.push_back(path);
for(int i=start;i<(int)nums.size();i++) {
path.push_back(nums[i]);
dfs(i+1);
path.pop_back();
}
};
dfs(0);
return res;
}
};/**
* @param {number[]} nums
* @return {number[][]}
*/ var subsets = function(nums) {
const res=[];
function dfs(start,path) {
res.push(path.slice());
for(let i=start;i<nums.length;i++) {
path.push(nums[i]);
dfs(i+1,path);
path.pop();
}
}
dfs(0,[]);
return res;
};