Saturday, January 3, 2015

Subsets (LeetCode Array)

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

Idea: Brute force. There are many ways to list all the combinations. I only write the recursion method and the iterative method as following.

Time: O(2^n) Space: O(n) for recursive, O(1) for iterative.

Recursive Code:
 public class Solution {  
   public List<List<Integer>> subsets(int[] S) {  
     List<List<Integer>> result=new ArrayList<List<Integer>>();  
     if(S==null||S.length==0)  
       return result;  
     Arrays.sort(S);  
     List<Integer> path=new ArrayList<Integer>();  
     dfs(result,path,S,0);  
     return result;  
   }  
   public void dfs(List<List<Integer>> result, List<Integer> path, int[] S, int start)  
   {  
     result.add(new ArrayList<Integer>(path));  
     for(int i=start;i<S.length;i++)  
     {  
       path.add(S[i]);  
       dfs(result,path,S,i+1);  
       path.remove(path.size()-1);  
     }  
   }  
 }  

Iterative Code:
 public class Solution {  
   public List<List<Integer>> subsets(int[] S) {  
     Arrays.sort(S);  
     List<List<Integer>> result=new ArrayList<List<Integer>>();  
     result.add(new ArrayList<Integer>());  
     for(int i=0;i<S.length;i++)  
     {  
       int curSize=result.size();  
       for(int j=0;j<curSize;j++)  
       {  
         List<Integer> cur=new ArrayList<Integer>(result.get(j));  
         cur.add(S[i]);  
         result.add(cur);  
       }  
     }  
     return result;  
   }  
 }  

No comments:

Post a Comment