LeetCode-Subsets II

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

[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]

解法一:从位表示,0表示不取,1表示取。
 public List<List<Integer>> subsetsWithDup(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> lists = new LinkedList<List<Integer>>();
        int max = 1 << nums.length;
        Set<List<Integer>> listSet = new HashSet<List<Integer>>();
        for(int i=0; i<max; i++) {
            int current = i;
            int index = nums.length-1;
            List<Integer> list = new LinkedList<Integer>();
            while(current != 0) {
                if((current & 1) == 1) {
                    list.add(0,nums[index]);
                }
                current >>= 1;
                index--;
            }
            if(!listSet.contains(list)) {
                lists.add(list);
                listSet.add(list);
            }
        }
        return lists;
    }

 

解法2:

先解决从一个集合中选K个元素的问题,然后用一次循环就能解决。

List<List<Integer>> lists = new LinkedList<List<Integer>>();
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        Arrays.sort(nums);
        for(int i=0; i<=nums.length; i++) {
            selectKElement(nums,  i, new LinkedList<Integer>(), 0);
        }
        return lists;
    }
    
    public void selectKElement(int[] nums, int k, List<Integer> list, int start) {
        if(list.size() == k) {
            lists.add(new LinkedList<Integer>(list));
        } else {
            for(int i=start; i<nums.length; i++) {
                if(i>start && nums[i] == nums[i-1])
                    continue;
                list.add(nums[i]);
                selectKElement(nums, k, list, i+1);
                list.remove(list.size()-1);
            }
        }
    }

 

posted on 2015-05-07 19:47  linxiong1991  阅读(117)  评论(0编辑  收藏  举报

导航