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

  1. At each index, decide: include or exclude current element
  2. Backtracking: add element, recurse, remove element
  3. Base case: when index reaches end, add current subset to result
  4. Total subsets = 2^n

Related Data Structures & Algorithms exercises

Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler