[leedcode 90] 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],
  []
]
public class Solution {
    List<Integer> seq;
    List<List<Integer>> res;
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        //本题和Subsets的不同就是需要对重复值进行处理,增加了一个判断,
        //需要注意判断的范围,i首先要满足i>start
        seq=new ArrayList<Integer>();
        res=new ArrayList<List<Integer>>();
        Arrays.sort(nums);
        getSub(nums,0,nums.length);
        return res;
    }
    public void getSub(int[] nums,int start,int end){
        if(start<=end){
            res.add(new ArrayList<Integer>(seq));
        }
        for(int i=start;i<end;i++){
            if(i>start&&nums[i]==nums[i-1])continue;
            seq.add(nums[i]);
            getSub(nums,i+1,end);
            seq.remove(seq.size()-1);
            //while(i<nums.length-1&&nums[i]==nums[i+1]) i++;
        }
    }
}

 

posted @ 2015-07-16 12:33  ~每天进步一点点~  阅读(188)  评论(0编辑  收藏  举报