Sunday, January 4, 2015

Subsets II (LeetCode Array)

Question: Given a collection of integers that might contain duplicates, 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,2], a solution is:
[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]

Idea: Brute force. The only thing is to skip the adjacent duplicates.

Time: O(2^n) Space: O(1)

Iterative Code:
 public class Solution {  
   public List<List<Integer>> subsetsWithDup(int[] num) {  
     List<List<Integer>> result=new ArrayList<List<Integer>>();  
     result.add(new ArrayList<Integer>());  
     Arrays.sort(num);  
     int preSize=0;  
     for(int i=0;i<num.length;i++)  
     {  
       int curSize=result.size();  
       for(int j=0;j<curSize;j++)  
       {  
         if(i==0||num[i]!=num[i-1]||j>=preSize)  
         {  
           List<Integer> oneRow=new ArrayList<Integer>(result.get(j));  
           oneRow.add(num[i]);  
           result.add(oneRow);  
         }  
       }  
       preSize=curSize;  
     }  
     return result;  
   }  
 }  

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

No comments:

Post a Comment