← Backtracking

Subsets

Medium
Python
def subsets(nums):
    res=[[]]
    for n in nums:
        res+=[s+[n] for s in res]
    return res
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
  • res += [...] extends list
  • Iterative power set identical
Python
def subsets(nums):
    res=[[]]
    for n in nums:
        res+=[s+[n] for s in res]
    return res
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
2. For each element add to all