Subsets (Power Set) in Java: Explanation & Practice
Generate all subsets of a set
Problem summary
Given an array of unique integers, return all possible subsets (the power set). Include the empty set and the set itself.
Starter code
public class Main {
public static void main(String[] args) {
int[] nums = {1, 2, 3};
// Backtracking: for each element, include or exclude
// Start with empty subset, add elements one by one
// Print all subsets, one per line
}
}Expected output and test cases
- [1,2,3] → 8 subsets
[] [1] [1,2] [1,2,3] [1,3] [2] [2,3] [3]
- [0] → 2 subsets
[] [0]
- [] → just empty set
[]
Hints
- At each index, decide: include or exclude current element
- Backtracking: add element, recurse, remove element
- Base case: when index reaches end, add current subset to result
- Total subsets = 2^n
Related Data Structures & Algorithms exercises
- Practice Koko Eating Bananas in Java
- Practice Capacity To Ship Packages in Java
- Practice Permutations in Java
Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler