Practice LeetCode 78 · Subsets · GFG · Power Set
RecursionBacktrackingSubsetsPower Set

Subsets · Power Set

Generate every subset of a set. For each element there are exactly two choices, take it or leave it, so the whole search is a binary decision tree with 2ⁿ leaves.

Include or exclude

Walk the elements left to right. At index i, branch two ways: include nums[i] in the path, or skip it. Recurse to i+1 each way.

When you run past the last index, the path is one complete subset, record it.

Why 2ⁿ

  • n elements, each an independent yes/no
  • 2 × 2 × … × 2 = 2ⁿ combinations
  • Leaves of the tree = the 2ⁿ subsets
  • Includes both {} and the full set

Enumerate every subset

Unvisited Active Subset recorded Backtracked
current path:
slowfast
Step 0
Nodes explored
0
Subsets found
0
Expected 2ⁿ
–
Depth
0

C++

void dfs(int i, vector<int>& nums,
         vector<int>& path, vector<vector<int>>& out) {
    if (i == nums.size()) {          // leaf: one complete subset
        out.push_back(path);
        return;
    }
    // choice 1: include nums[i]
    path.push_back(nums[i]);
    dfs(i + 1, nums, path, out);
    path.pop_back();                 // backtrack

    // choice 2: exclude nums[i]
    dfs(i + 1, nums, path, out);
}

vector<vector<int>> subsets(vector<int>& nums) {
    vector<vector<int>> out;
    vector<int> path;
    dfs(0, nums, path, out);
    return out;                       // 2^n subsets
}
Time
O(2ⁿ · n)

2ⁿ subsets, each up to length n to copy into the output.

Space
O(n)

Recursion depth and the working path, output excluded.

Output
2ⁿ

The count of subsets, from empty set to the full set.

  • Two equivalent shapes: the binary include/exclude tree shown here, or the "start-index loop" that adds a subset at every node. Same 2ⁿ result.
  • For duplicate elements (LC 90), sort first and skip nums[i]==nums[i-1] on the exclude branch to avoid repeat subsets.
  • The bitmask trick is the iterative twin: numbers 0…2ⁿ-1, bit j set means include element j.
  • Recording at leaves gives full subsets; recording at every node gives all prefixes, pick per problem.
  • This exact tree underlies combination sum, partitioning, and most "generate all" problems.