LeetCode-subsets

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:

[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]
import java.util.*;
public class Solution {
    public ArrayList<ArrayList<Integer>> subsets(int[] S) {
         ArrayList<ArrayList<Integer>> result=new ArrayList<ArrayList<Integer>>();
        Arrays.sort(S);
        ArrayList<Integer> subList=new ArrayList<Integer>();
        for (int i=0;i<=S.length;i++){
            func(S,i,0,subList,result);
        }
        return result;
         
    }
    public void func(int[] S,int num,int index,ArrayList<Integer> subList,ArrayList<ArrayList<Integer>> result){
        if (num<0){
            return;
        }else if (num==0){
            result.add(new ArrayList<Integer>(subList));
        }else {
            for (int j=index;j<S.length;j++){
                subList.add(S[j]);
                func(S,num-1,j+1,subList,result);
                subList.remove(subList.size()-1);
            }
 
        }
    }
     
}

 

上一篇:78,90,Subsets,46,47,Permutations,39,40 DFS 大合集


下一篇:78. Subsets(M, dfs)