← All coding problems
Subsets
mediumRecursion & Backtracking+20 XPTime limit 2s
The array has distinct integers. Print all its subsets (the power set), including the empty one.
Input:
- line 1:
n - line 2:
ndistinct integers
Output: one subset per line in the form [a b c] (the empty subset is []). So there is exactly one correct output:
- list the numbers inside each subset in increasing order;
- list the subsets in lexicographic order — compare them number by number, and a subset that is a prefix of another comes first (
[],[1],[1 2],[1 2 3],[1 3],[2], …).
Constraints: 1 ≤ n ≤ 12, −100 ≤ value ≤ 100.
Think about it: sort first. Then the classic backtracking — "print the current subset, then for every later element: add it, recurse, remove it" — produces exactly this order.
Sample input 1
3 1 2 3
Sample output 1
[] [1] [1 2] [1 2 3] [1 3] [2] [2 3] [3]
Sample input 2
1 0
Sample output 2
[] [0]
📖 Stuck? Learn the pattern
Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).