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 = [1,2,3]
, a solution is:
DSF:和combination 的方法一样,再加一个控制mem.size 的外层循坏!
package leetcode2;
import java.util.*;
public class subset {
public static ArrayList<ArrayList<Integer>> subset(int[] n){
ArrayList<ArrayList<Integer>> res=new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> mem=new ArrayList<Integer>();
int deep=0;
for(int i=0;i<=n.length;i++){
dfs(res,mem,deep,n,i);
}
return res;
}
public static void dfs(ArrayList<ArrayList<Integer>> res,
ArrayList<Integer> mem, int deep,int[] n,int i) {
// TODO Auto-generated method stub
if(mem.size()==i){
ArrayList<Integer> re= new ArrayList<Integer>(mem) ;
Collections.sort(re);
if(!res.contains(re)){
res.add(re);
}
return;
}
for(int i1=deep;i1<n.length;i1++){
mem.add(n[i1]);
dfs(res,mem,i1+1,n,i);
if(mem.size()>0){
mem.remove(mem.size()-1) ;
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] a={1,2,3,8};
System.out.println(subset(a));
}
}