def subsets(nums):
result=[[]]
for n in nums:
result+=[s+[n] for s in result]
return result
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;
}
Python list comprehension concise. Java needs explicit loops.
def subsets(nums):
result=[[]]
for n in nums:
result+=[s+[n] for s in result]
return result
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;
}
1. Start with empty set 2. For each element add to all existing