078. Subsets
At a Glance
- Topic: Array
- Pattern: Analyze Pattern
- Difficulty: Medium
- LeetCode: 078
Problem Statement
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]]
Example 2:
Input: nums = [0] Output: [[],[0]]
Constraints:
1 <= nums.length <= 10
-10 <= nums[i] <= 10
All the numbers of nums are unique.Approach & Solution Steps
- 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 JS Solution
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;
}Edge Cases & Pitfalls
- Always consider empty or null inputs.
- Watch out for off-by-one index errors.
Mark this page when you finish learning it.
Last updated on
Spotted something unclear or wrong on this page?