V

Algorithm Visualizer

ZHEN
Share on WeiboShare on XGitHub repositoryAuthor website
Learning ToolsAlgorithm Complexity ReferenceAlgorithm Learning Paths
Data StructuresArrayLinked ListStackQueue and DequeBinary Search TreeBinary HeapHash TableGraphTrieDisjoint Set UnionLRU CacheSkip ListSegment TreeB+ TreeBloom FilterFenwick Tree
SortingBubble SortCocktail Shaker SortBitonic SortSelection SortInsertion SortBinary Insertion SortShell SortMerge SortTop-Down Merge SortQuick SortThree-Way Quick SortDual-Pivot Quick SortHeap SortCounting SortRadix SortBucket Sort
Graph AlgorithmsDijkstra's Shortest PathKruskal's Minimum Spanning TreePrim's Minimum Spanning TreeBellman-Ford Shortest PathsTopological SortFloyd-WarshallStrongly Connected Components2-SATMaximum FlowBipartite MatchingLowest Common AncestorEulerian Path
Dynamic ProgrammingEdit Distance0/1 KnapsackUnbounded KnapsackLongest Common SubsequenceLongest Increasing SubsequenceCoin ChangeStone MergingTraveling Salesperson DPTree Dynamic ProgrammingDigit DPRerooting DP
Backtracking and SearchN-QueensSubsetsPermutationsCombination SumMaze Solving with DFSNumber of IslandsWord SearchSudoku SolverA* Search
StringsKMP String MatchingRabin-Karp String MatchingBoyer-Moore String MatchingManacher's Longest Palindromic SubstringSuffix ArrayLCP ArrayAho-Corasick AutomatonZ Function
Math and Number TheorySieve of EratosthenesLinear SieveEuclidean AlgorithmBinary ExponentiationExtended Euclidean AlgorithmChinese Remainder TheoremEuler's Totient FunctionMiller-Rabin Primality TestFast Fourier TransformPollard's Rho Factorization
Computational GeometryConvex HullRotating CalipersClosest Pair of PointsLine Segment IntersectionBentley-Ottmann Sweep Line
SearchingBinary SearchLower and Upper BoundSearch in a Rotated Sorted ArrayBinary Search on the AnswerTernary Search

Subsets

Generate a power set through an include-or-exclude decision tree

Make one binary decision per element

Every subset of an n-element set is determined by n decisions: include the next element or exclude it. Those choices form a complete binary tree of depth n, with one subset at each of its 2^n leaves.

Traverse the decision tree depth first

Follow the include branch, recurse, undo that choice, then follow the exclude branch. The highlighted root-to-node path is the current recursion stack. Reaching a leaf means every element has a decision, so the current subset can be recorded.

The player expands all choices for [1, 2, 3]. Visited nodes remain visible, green leaves are recorded subsets, and the edge labels make every include or exclude operation explicit.

Include 1Include 2Include 3Exclude 3Exclude 2Include 3Exclude 3Exclude 1Include 2Include 3Exclude 3Exclude 2Include 3Exclude 3{1,2,3}{1,2}{1,3}{1}{2,3}{2}{3}∅

Start at the empty set and decide whether to include each element in order.

1function subsets(nums: number[]): number[][] {
2 const res: number[][] = [];
3 const cur: number[] = [];
4 const backtrack = (i: number): void => {
5 if (i === nums.length) {
6 res.push([...cur]);
7 return;
8 }
9 cur.push(nums[i]); // include nums[i]
10 backtrack(i + 1);
11 cur.pop(); // undo (backtrack)
12 backtrack(i + 1); // exclude nums[i]
13 };
14 backtrack(0);
15 return res;
16}
Elements1 2 3
Current subset∅
Recorded0 / 8
1 / 31

Output size sets the lower bound

There are 2^n subsets. Materializing each result may copy up to n values, so the total time and output space are O(n * 2^n). The active recursion path itself uses only O(n) space.

Invariant: each root-to-leaf path assigns one distinct include/exclude bit to every element, so the traversal produces every subset exactly once.

Add constraints and pruning to the same decision-tree model in N-Queens.