Tuesday, February 11, 2014

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],
  []
]
Solution:
n->n+1
public class Solution {
    public ArrayList<ArrayList<Integer>> subsets(int[] S) {
        Arrays.sort(S);
        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
        if(S.length == 0) return result;
        result.add(new ArrayList<Integer>());
        for(int i = 0; i < S.length; i++){
            ArrayList<ArrayList<Integer>> prev = new ArrayList<ArrayList<Integer>>();
            for(ArrayList<Integer> iter : result){
                ArrayList<Integer> cur = new ArrayList<Integer>(iter); // must new!!!!!
                cur.add(S[i]);
                prev.add(cur);
            } 
            for(int j = 0; j < prev.size(); j++){ // cannot assign reference type directly
                result.add(j, prev.get(j));
            }
        }
        return result;
    }
}

No comments:

Post a Comment