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],
  []
]
题意:给出n个数,按非递减顺序给出,求其所有的组合 
思路:与Subsets(求所有的组合)处理方法有些类似,只是在取一个元素时,分为取和不取两种情况,但是在元素有重复情况时,就分为取0, 1,2,...直到取n的情况,与元素重复的个数有关。
代码如下:
 
  
public class Solution {

    private List> dfs(HashMap m, int[] nums, int cur)
    {
        List> res = new LinkedList>();

        /*空组合*/
        if (cur == nums.length) {
            List ans = new LinkedList();
            res.add(ans);
            return res;
        }

        /*表示从第cur+1到n之间的数生成的组合*/
        List> ret = dfs(m, nums, cur + 1);
        res.addAll(ret);

        /*第cur个数的出现次数*/
        int num = m.get(nums[cur]);
        for (List list : ret) {

            List tmp2 = new LinkedList();
            tmp2.addAll(list);
            /*表示第cur个数取1个直到取num个的处理*/
            for (int i = 0; i < num; i++) {
                List tmp = new LinkedList();
                tmp2.add(0, nums[cur]);
                tmp.addAll(tmp2);
                res.add(tmp);
            }
        }
        return res;
    }

    public List> subsetsWithDup(int[] nums)
    {
        /*统计每个数的出现次数*/
        HashMap hs = new HashMap();
        for (int i = 0, len = nums.length; i < len; i++) {
            if (hs.containsKey(nums[i])) {
                int value = hs.get(nums[i]);
                hs.put(nums[i], value + 1);
            } else {
                hs.put(nums[i], 1);
            }
        }

        int[] array = new int[hs.size()];
        int i = 0;
        for (Integer a : hs.keySet()) {
            array[i++] = a;
        }
        return dfs(hs, array, 0);
    }
}

你可能感兴趣的:(#,#,数论)