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

Subsets II ——LeetCode

时间:2015-05-01 17:21:12      阅读:113      评论: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],
  []
]

题目大意:给定一个数组,返回所有的可能子集合,数组有重复元素,但是子集合不能重复。

解题思路:这题我首先sort一下,然后遍历,当前元素不是重复的元素就把res里的所有的list取出来加上当前的元素再添加到res里,是重复元素就把上一次加入res的此元素list取出并加上重复元素再放入res。

    public List<List<Integer>> subsetsWithDup(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        if (nums == null || nums.length == 0) {
            return res;
        }
        Arrays.sort(nums);
        res.add(new ArrayList<Integer>());
        int lastSize = 0, currSize;
        for (int i = 0; i < nums.length; i++) {
            int start = (i > 0 && nums[i] == nums[i - 1]) ? lastSize : 0;
            currSize = res.size();
            for (int j = start; j < currSize; j++) {
                List<Integer> tmp = new ArrayList<>(res.get(j));
                tmp.add(nums[i]);
                res.add(tmp);
            }
            lastSize = currSize;
        }
        return res;
    }

 

Subsets II ——LeetCode

标签:

原文地址:http://www.cnblogs.com/aboutblank/p/4470888.html

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