DSA AnimatorDSA animations
Subsets LC #78 Medium Backtracking · Power Set
Problem

Given an integer array nums of unique elements, return all possible subsets (the power set). The solution set must not contain duplicate subsets. Return the solution in any order.

Example 1
Input: nums = [1,2,3]
Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
Explanation: 2³ = 8 subsets for 3 elements.
Example 2
Input: nums = [0]
Output: [[],[0]]
Constraints: 1 ≤ nums.length ≤ 10  |  −10 ≤ nums[i] ≤ 10  |  All numbers are unique.
Try Examples
Custom:
Approach
Backtracking — Add at Every Node
Add curr to results at every recursive call (not just leaves). For each element from start: include → recurse with i+1 → backtrack (remove). Generates all 2^n subsets.
Input Array
Current Subset
curr = [ ] (empty)
Recursion Tree
Results 0 collected
Variables
curr
[ ]
start
—
subsets found
0
Step Logic
Press ▶ Play or Next Step to begin.
✅
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
Add current subset at EVERY call (including empty set)
2
For each i from start: include nums[i], recurse with i+1, then backtrack (remove)
3
Base case: loop exhausted → implicit return (curr was already added)
4
2^n subsets total for n elements
Time
O(n·2^n)
Space
O(n)
Why Backtracking Works

Unlike combinations, we add curr to results at every recursive call — this captures all subsets including the empty set. The for loop starting at start prevents duplicates by only going forward. Each element is either included or excluded, giving 2^n total paths.

How to solve Subsets

LeetCode 78 · Medium · Backtracking · Pattern: Backtracking

Why the obvious approach is slow

Each number is either in or out, so there are 2 to the power n subsets. We can generate them as a recursion tree where every node is one subset.

The key idea

Start with an empty path, and record it as a subset. From index start, add each later number, recurse, and then remove it again. Only moving forward keeps every subset unique, because 2, 1 is never built after 1, 2.

Remember

Choose, explore, then un-choose. Every node of the tree is a subset, so record it on entry.

Run the animation above on your own input, or watch the 1:19 video explanation of Subsets with a dry run and Java code.

More Backtracking problems