分享

[LeetCode 90] Subsets II

 雪柳花明 2016-10-05

题目链接:subsets-ii


[java] view plain copy
  1. import java.util.ArrayList;  
  2. import java.util.Arrays;  
  3. import java.util.HashSet;  
  4. import java.util.List;  
  5. import java.util.Set;  
  6.   
  7. /** 
  8.  *  
  9.         Given a collection of integers that might contain duplicates, S, return all possible subsets. 
  10.          
  11.         Note: 
  12.         Elements in a subset must be in non-descending order. 
  13.         The solution set must not contain duplicate subsets. 
  14.         For example, 
  15.         If S = [1,2,2], a solution is: 
  16.          
  17.         [ 
  18.           [2], 
  19.           [1], 
  20.           [1,2,2], 
  21.           [2,2], 
  22.           [1,2], 
  23.           [] 
  24.         ] 
  25.  * 
  26.  */  
  27.   
  28. public class SubsetsII {  
  29.   
  30. //  19 / 19 test cases passed.  
  31. //  Status: Accepted  
  32. //  Runtime: 259 ms  
  33. //  Submitted: 0 minutes ago  
  34.       
  35.     //时间复杂度O(2^n) 空间复杂度 O(n)  
  36.     //偷懒了,直接用了set容器,去除重复子集  
  37.     public Set<List<Integer>> subsets = new HashSet<List<Integer>>();  
  38.     public List<List<Integer>> subsetsWithDup(int[] num) {  
  39.         Arrays.sort(num);  
  40.         subsets(num, 0new ArrayList<Integer>());  
  41.         return new ArrayList<List<Integer>>(subsets);        
  42.     }  
  43.     public void subsets(int[] S, int step, List<Integer> subset) {  
  44.         if(step == S.length) {  
  45.             subsets.add(subset);  
  46.             return;  
  47.         }  
  48.         //num[step] 不加入子集中  
  49.         subsets(S, step + 1new ArrayList<Integer>(subset));  
  50.           
  51.         //num[step] 加入子集中  
  52.         subset.add(S[step]);          
  53.         subsets(S, step + 1new ArrayList<Integer>(subset));          
  54.     }  
  55.       
  56.     public static void main(String[] args) {  
  57.         // TODO Auto-generated method stub  
  58.   
  59.     }  
  60.   
  61. }  


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多