Example code
This example generates all subsets of an array:How it works
The subset generation algorithm works by making a binary decision for each element:- Base case: When
i == 0, all elements have been considered - add the current subset to results - Recursive cases: For each element at position
i-1:- Exclude: Continue without adding the element
- Include: Add the element to current_subset and continue
- Left branches represent excluding the current element
- Right branches represent including the current element
For an array of size n, this algorithm generates 2^n subsets. The recursion tree has 2^n leaf nodes, each representing one unique subset.
Decorator configuration
The@vs decorator is configured for optimal visualization:
ignore_args=["nums"]: Hides the input array since it remains constantshow_return_value=False: Hides return values (function returns None)show_argument_name=False: Shows only values for cleaner nodes
i and the growing current_subset.
Output
Running this code withnums=[1, 2, 3] generates:
- Console output: None (subsets are stored in the global
subsetslist) - Subsets generated:
[[], [1], [2], [2, 1], [3], [3, 1], [3, 2], [3, 2, 1]] - Animation file:
subset.gifshowing the binary decision tree with a 3-second delay between frames
Visualization insights
In the recursion tree, you can observe:- The tree depth equals the number of elements in the input array
- Each level represents a decision about one element
- The path from root to leaf represents which elements to include (right branches) or exclude (left branches)
- All 2^n possible combinations are explored