78. Subsets
At a Glance
- Topic: backtracking
- Pattern: DFS / Backtracking
- Difficulty: Medium
- Companies: Amazon, Meta, Google, Microsoft, Bloomberg
- Frequency: Very High
- LeetCode: 78
Problem (one-liner)
Given distinct integers nums, return the power set: all 2^n subsets (including empty and full set). Order of subsets or elements may vary unless constrained.
Recognition Cues
- All subsets / power set
- Input values distinct
- Classic inclusion/exclusion at each index
Diagram
At-a-glance flow (replace with problem-specific Mermaid as you refine this note). camelCase node IDs; no spaces in IDs.
Loading diagram…
Approaches
- Iterative — bit mask
0..2^n-1—O(n * 2^n)time. - Optimal — DFS backtrack choose/skip each index — same complexity, cleaner recursion tree.
Optimal Solution
Go
func subsets(nums []int) [][]int {
result := [][]int{}
path := make([]int, 0, len(nums))
var dfs func(start int)
dfs = func(start int) {
copied := make([]int, len(path))
copy(copied, path)
result = append(result, copied)
for index := start; index < len(nums); index++ {
path = append(path, nums[index])
dfs(index + 1)
path = path[:len(path)-1]
}
}
dfs(0)
return result
}JavaScript
function subsets(nums) {
const result = [];
const path = [];
function dfs(startIndex) {
result.push([...path]);
for (let index = startIndex; index < nums.length; index += 1) {
path.push(nums[index]);
dfs(index + 1);
path.pop();
}
}
dfs(0);
return result;
}Walkthrough
nums = [1,2,3]. DFS builds [], then branches include 1 → [1], deeper [1,2], [1,2,3], backtrack, [1,3], etc.
Invariant: Each recursive depth considers elements from start onward only—no duplicate subsets.
Edge Cases
- Empty
nums→[[]] - Single element →
[[],[x]]
Pitfalls
- Pushing
pathreference without copy → mutation bugs in Go/JS - Duplicates in input — use 90 instead
Similar Problems
- 90. Subsets II — duplicates, skip duplicates
- 46. Permutations — order matters; uses swap or chosen set
Variants
- Bitmask enumeration — iterative companion to DFS
- Size-k subsets only — prune when
len(path) === k
Mind-Map Tags
#backtracking #subsets #power-set #dfs #recursion
Last updated on
Spotted something unclear or wrong on this page?