Backtracking is DFS over decisions. For subsets the decision at each element is simply "take it or leave it", which makes this the cleanest introduction to the pattern.
A pizza counter lets you choose any selection of its toppings, from none at all to the lot. Given the list nums of distinct topping codes, write subsets(nums) that returns every possible selection (together they form the power set), each as a list. The selections may come in any order and so may the codes inside each one, but no selection may appear twice.
Examples
Input: nums = [3, 5, 8]
Output: [[], [3], [5], [3, 5], [8], [3, 8], [5, 8], [3, 5, 8]]
Input: nums = [9]
Output: [[], [9]]
Constraints
0 <= len(nums) <= 10, all values distinct- Target: O(n * 2^n) time (you cannot do better: that is the size of the output)
Goals
- Apply the choose / explore / un-choose backtracking template
- Generate every subset by deciding, for each element, whether to include it
- Copy the current path when recording a result instead of storing a reference to it