← Recursion

Power Set

Medium
Python
def subsets(nums):
    result=[[]]
    for n in nums:
        result+=[s+[n] for s in result]
    return result
Java
public List<List<Integer>> subsets(int[] nums){
    List<List<Integer>> res=new ArrayList<>();
    res.add(new ArrayList<>());
    for(int n:nums){
        int size=res.size();
        for(int i=0;i<size;i++){
            List<Integer> sub=new ArrayList<>(res.get(i));
            sub.add(n); res.add(sub);
        }
    } return res;
}

Key Insight

Python list comprehension concise. Java needs explicit loops.

Python → Java Differences

  • List comprehension vs explicit loop
  • result += [...] extends list
  • Iterative power set identical
Python
def subsets(nums):
    result=[[]]
    for n in nums:
        result+=[s+[n] for s in result]
    return result
Java
public List<List<Integer>> subsets(int[] nums){
    List<List<Integer>> res=new ArrayList<>();
    res.add(new ArrayList<>());
    for(int n:nums){
        int size=res.size();
        for(int i=0;i<size;i++){
            List<Integer> sub=new ArrayList<>(res.get(i));
            sub.add(n); res.add(sub);
        }
    } return res;
}

Algorithm Steps

1. Start with empty set
2. For each element add to all existing