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],
  []
]

When loop the array, add the current element to the results.

public List<List<Integer>> subsets(int[] S) {
        if (S==null) {
            return null;
        }
        List<List<Integer>> results = new ArrayList<List<Integer>>();
        //All [] is a subset
        results.add(new ArrayList<Integer>());

        Arrays.sort(S);

        subsets(new ArrayList<Integer>(), results, 0, S);
        return results;        
    }

    public void subsets(List<Integer> result, List<List<Integer>> results, int level, int[] S) {
            for (int i=level; i<S.length; i++) {
                result.add(S[i]);                
                results.add(new ArrayList<Integer>(result));
                subsets(result, results, i+1, S);
                result.remove(result.size()-1);                
            }
    }