Power Set (All Subsets)
Generate all possible subsets of a set. Total 2^n subsets for n elements. Classic backtracking problem.
Visualization
Interactive visualization for Power Set (All Subsets)
Power Set Generation
• Time: O(2^n × n)
• Space: O(2^n × n)
• Generates all 2^n subsets
Interactive visualization with step-by-step execution
Implementation
1function subsets(nums: number[]): number[][] {
2 const result: number[][] = [];
3
4 const backtrack = (index: number, current: number[]): void => {
5 result.push([...current]);
6
7 for (let i = index; i < nums.length; i++) {
8 current.push(nums[i]);
9 backtrack(i + 1, current);
10 current.pop();
11 }
12 };
13
14 backtrack(0, []);
15 return result;
16}
17
18// Bit manipulation approach
19function subsetsBitMask(nums: number[]): number[][] {
20 const result: number[][] = [];
21 const n = nums.length;
22
23 for (let mask = 0; mask < (1 << n); mask++) {
24 const subset: number[] = [];
25 for (let i = 0; i < n; i++) {
26 if (mask & (1 << i)) {
27 subset.push(nums[i]);
28 }
29 }
30 result.push(subset);
31 }
32
33 return result;
34}Deep Dive
Theoretical Foundation
For each element, make two recursive choices: include it or exclude it. Builds solution tree with 2^n leaves. Can also use bit manipulation or iterative approach.
Complexity
Time
O(2^n)
O(2^n)
O(2^n)
Space
O(2^n)
Applications
Use Cases
Related Algorithms
N-Queens Problem
The N-Queens Problem asks: place N chess queens on an N×N chessboard so that no two queens threaten each other. This means no two queens can be on the same row, column, or diagonal. It's a classic constraint satisfaction problem that demonstrates backtracking, pruning, and systematic exploration of solution spaces. The problem has applications in parallel processing, resource allocation, and algorithm design education.
Sudoku Solver
Sudoku Solver uses backtracking to fill a 9×9 grid with digits 1-9, ensuring each row, column, and 3×3 box contains all digits exactly once. This classic constraint satisfaction problem demonstrates systematic exploration with constraint checking. The algorithm fills empty cells one by one, backtracking when constraints are violated, making it a perfect example of pruning in search algorithms.
Combination Sum
Find all unique combinations in array where chosen numbers sum to target. Numbers can be reused. Classic backtracking problem with pruning optimization.
Generate Valid Parentheses
Generate all combinations of n pairs of well-formed parentheses. Uses backtracking with constraint that closing parentheses never exceed opening ones.