List every subset of a set of different numbers, using backtracking.
What to build
A program that prints all subsets in the order that depth-first backtracking finds them.
Requirements
- Take the numbers in input order and use the choose, explore, un-choose pattern.
- Print one subset per line, its numbers separated by spaces, and
emptyfor the empty subset.
Input
The first line has n. The second line has the n different integers.
Output
All 2ⁿ subsets, one per line, in backtracking order.
Constraints
1 ≤ n ≤ 10.
Example
Input:
3
1 2 3
Output:
empty
1
1 2
1 2 3
1 3
2
2 3
3
Why it works
Every path from the root of the search is a subset. Starting each loop after the last chosen position means no subset is produced twice in a different order, and the pop restores the path for the next branch.
Examples
3 1 2 3
empty 1 1 2 1 2 3 1 3 2 2 3 3
1 5
empty 5
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Record the current path at every call: each path is one subset.
Hint 2
Loop i from start to the end: append items[i], recurse with i + 1, then pop.
Hint 3
Print the empty subset as `empty`.
Solution
Show one correct solution (try it yourself first)
n = int(input())
nums = input().split()
path = []
def backtrack(start):
print(*path if path else ["empty"])
for i in range(start, n):
path.append(nums[i])
backtrack(i + 1)
path.pop()
backtrack(0)
▶ Open this solution in the compiler, then press Visualize to watch it run step by step