Recursion / Backtracking
Subsets
Generate all possible subsets of a given array using recursion and backtracking.
Intuition
For every element we have two choices: either include it in the subset or exclude it. This naturally forms a recursion tree.
Algorithm
- Start recursion from index 0
- Include current element
- Move to next index
- Backtrack by removing element
- Exclude current element
Dry Run
[]
[1]
[1,2]
[2]
[1]
[1,2]
[2]
Python Solution
class Solution:
def subsets(self, nums):
ans = []
def backtrack(i, curr):
if i == len(nums):
ans.append(curr[:])
return
curr.append(nums[i])
backtrack(i + 1, curr)
curr.pop()
backtrack(i + 1, curr)
backtrack(0, [])
return ans