Subsets II ——LeetCode

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;

    }

 

你可能感兴趣的:(LeetCode)