题目详见leetcode
public class Solution {
public ArrayList<ArrayList<Integer>> subsets(int[] S) {//http://blog.csdn.net/linhuanmars/article/details/24286377
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> line = new ArrayList<Integer>();
if(S==null||S.length==0) return res;
Arrays.sort(S); // must have
res.add(line);
for(int i=0;i<S.length;i++){
int size = res.size();
for(int j=0;j<size;j++){ 因为过程中res.size会变, 而第二层loop是为了遍历当前未变化res中的subset集合
//ArrayList<Integer> tmp = res.get(j);
ArrayList<Integer> tmp = new ArrayList<Integer>(res.get(j));
tmp.add(S[i]);
res.add(tmp);
}
}
return res;
}}
public class Solution {
public ArrayList<ArrayList<Integer>> subsetsWithDup(int[] num) {
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
if(num==null||num.length==0) return res;
res.add(new ArrayList<Integer>());
Arrays.sort(num);
int start =0;
for(int i=0; i < num.length;i++){
int size =res.size();
// for(int j=0;j<size();j++){// !!!!!
for(int j=start;j<size;j++){
ArrayList<Integer> tmp = new ArrayList<Integer>(res.get(j));
tmp.add(num[i]);
res.add(tmp);
}
if(i<num.length-1&&num[i]==num[i+1]){
start=size; // 跳过已经重复元素加过的member!!!!
}else{start=0;}
}
return res;
}
}