example of using backtracking to generate all subsets of a given list
def generate_subsets(nums):
result = []
def backtrack(start, path):
# Append a shallow copy of the current subset path to the result
result.append(list(path))
# Explore subsequent elements to build deeper subsets
for i in range(start, len(nums)):
# 1. Choose: Include the current element
path.append(nums[i])
# 2. Explore: Move deeper down this decision tree branch
backtrack(i + 1, path)
# 3. Backtrack: Remove the element to explore other choices
path.pop()
# Start the recursion from index 0 with an empty tracking path
backtrack(0, [])
return resultExample Usage:
nums_list = [1, 2, 3]
print(generate_subsets(nums_list))