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<List<Integer>> dfs(HashMap<Integer, Integer> m, int[] nums, int cur)
    {
        List<List<Integer>> res = new LinkedList<List<Integer>>();

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

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

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

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

    public List<List<Integer>> subsetsWithDup(int[] nums)
    {
        /*统计每个数的出现次数*/
        HashMap<Integer, Integer> hs = new HashMap<Integer, Integer>();
        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);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kgduu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值