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],
  []
]
 1 public class Solution {
 2     public ArrayList<ArrayList<Integer>> subsets(int[] S) {
 3         // Start typing your Java solution below
 4         // DO NOT write main() function
 5         Arrays.sort(S);
 6         ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
 7         generate(result, new ArrayList<Integer>(), 0, S, S.length);
 8         return result;
 9     }
10     
11     public void generate(ArrayList<ArrayList<Integer>> result, ArrayList<Integer> output,
12                     int depth, int[] S, int len){
13         result.add(output);
14         if(depth == len){
15             return;
16         }
17         
18         for(int i = depth; i < len; i++){
19             ArrayList<Integer> tmp = new ArrayList<Integer>();
20             tmp.addAll(output);
21             tmp.add(S[i]);
22             generate(result, tmp, i + 1, S, len);
23         }
24     }
25 }

 

posted @ 2013-08-13 21:29  feiling  阅读(243)  评论(0编辑  收藏  举报