码迷,mamicode.com
首页 > 其他好文 > 详细

[leedcode 90] Subsets II

时间:2015-07-16 13:43:52      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:

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++;
        }
    }
}

 

[leedcode 90] Subsets II

标签:

原文地址:http://www.cnblogs.com/qiaomu/p/4650932.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!