Search
⌘K
Get Premium
Backtracking

Subsets

medium

DESCRIPTION (inspired by Leetcode.com)

Given an integer array nums of unique elements, return all possible subsets that can be made from the elements in nums.

The solution set must not contain duplicate subsets, and the subsets can be returned in any order.

Example 1:

Input:

nums = [1,2]

Output:

[[],[1],[2],[1,2]]

Example 2:

Input:

nums = [0]

Output:

[[],[0]]

Explanation

Let's start by figuring out how to incrementally generate all possible subsets of a given set, starting from an empty set. Doing so will help us visualize the "solution space tree" which we can then traverse using a depth-first search and a backtracking approach.
To generate all possible subsets, we can choose to either include or exclude each element in the set to generate all possible subsets. We'll walkthrough how to do this with a simple example where we generate all possible subsets of the set [1, 2, 3].

Step 1 (first element)

We start with an empty set []. We can either include or exclude the first element 1 to generate all possible subsets.
This gives us two possible subsets:
  1. Include 1 in the subset: [1]
  2. Exclude 1 from the subset: []
Subsets: [[], [1]]

Step 2 (second element)

Next, we move onto index = 1. For each of the subsets generated in the previous step, we can either include or exclude the element at index 1.
This gives us the following subsets:
  1. Include 2 in the subset: [2]
  2. Include 2 in the subset: [1, 2]
  3. Exclude 2 from the subset: [1]
  4. Exclude 2 from the subset: []
Subsets: [[], [1], [2], [1, 2]]

Step 3 (third element)

Finally, we move onto index = 2. For each of the subsets generated in the previous step, we can either include or exclude the element at index 2.
This gives us the following subsets:
  1. Include 3 in the subset: [3]
  2. Include 3 in the subset: [1, 3]
  3. Include 3 in the subset: [2, 3]
  4. Include 3 in the subset: [1, 2, 3]
  5. Exclude 3 from the subset: []
  6. Exclude 3 from the subset: [1]
  7. Exclude 3 from the subset: [2]
  8. Exclude 3 from the subset: [1, 2]
Visualized as a tree, we get the following:
[][1][1,2][1,2,3][1,2][1][1,3][1][][2][2, 3][2][][3][]

Writing the Backtracking Function

Once we have this tree, we can use depth-first search to write a recursive backtracking function that generates all possible subsets of a given set.
At each node, we need to know the current subset and the current index of the element of the set. These are the parameters we'll pass to our recursive function.
Solution
def dfs(index: int, path: List[int]):
At each node, we'll make two recursive calls: one where we add the current element to the subset and another where we don't add the current element to the subset.
Solution
def dfs(index: int, path: List[int]):
# base case
# add nums[index] to the current subset
path.append(nums[index])
dfs(index + 1, path)
# decision to not include nums[index]
# need to remove it from path
path.pop()
dfs(index + 1, path)
The base case is when index == len(nums), at which point we'll add the current subset to our list of valid subsets and return.
Solution
def dfs(index: int, path: List[int]):
if index == len(nums):
result.append(path[:])
return
# add nums[index] to the current subset
path.append(nums[index])
dfs(index + 1, path)
# decision to not include nums[index]
# need to remove it from path
path.pop()
dfs(index + 1, path)
In the main function, we'll initialize an empty list to store the subsets, and make the initial call to our recursive function with the starting index 0 and an empty path [].
Solution
from typing import List
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
def dfs(index: int, path: List[int]):
if index == len(nums):
result.append(path[:])
return
# include nums[index]
path.append(nums[index])
dfs(index + 1, path)
# exclude nums[index]
path.pop()
dfs(index + 1, path)
result = []
dfs(0, [])
return result

Your account is free and you can post anonymously if you choose.

Unlock Premium Coding Content

Interactive algorithm visualizations
Reading Progress

On This Page