Given a set of distinct integers, S, return all possible subsets.
Note:
- Elements in a subset must be in non-descending order.
- The solution set must not contain duplicate subsets.
For example,
If S =
If S =
[1,2,3]
, a solution is:[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
Solution:
Intuitively, the subset of set[n] is a set of all set[n-1] and set[n-1]"+" S[n]
eg. for S=[1,2,3]
null: We start from empty set, set[0]={};
1: set[1]={} and {1}={{}"+" 1};
1,2 : set[2]= set[1] + {set[1]"+"2} = {}, {1}, {2} and {1,2}
1,2,3: set[3] =set[2] + {set[2]"+"3} ={}, {1}, {2} ,{1,2} {3},{1,3}, {2,3} and {1,2,3}
public List<List<Integer>> subsets(int[] S) {
List<List<Integer>> res=new ArrayList<List<Integer>>();
if(S==null || S.length==0) return res;
Arrays.sort(S);
List<Integer> emptySet=new ArrayList<Integer>();
res.add(emptySet);
for(int i=0;i<S.length;i++){
int l=res.size();
for(int j=0;j<l;j++){
List<Integer> temp=new ArrayList<Integer>(res.get(j));
temp.add(S[i]);
res.add(temp);
}
}
return res;
}
No comments:
Post a Comment