LeetCode刷题笔录Subsets II

Given a collection of integers that might contain duplicates, S, 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 S = [1,2,2], a solution is:

[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]
比Subsets要求稍高的一点是这里会出现duplicate elements。想法是如果下一个元素是duplicate,那么在下一次循环中就不是遍历之前所有的solution set,而是只遍历前一次循环中新增加的Solution sets。以[1,2,2]为例:

start: []

itr1: [] [1]

itr2:[] [1] [2] [1,2]

如果itr3按照之前的做法对每个set都加入新的元素2,那么会产生重复:

[] [1] [2] [1,2] [2] [1,2] [1,2,2] [2,2]

可以看到只有[1,2,2]和[2,2]是我们需要新加入的solution set。

因此itr3只应该循环前一次循环新增加的部分

代码如下:

public class Solution {
    public List<List<Integer>> subsetsWithDup(int[] num) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        if(num == null || num.length == 0)
            return res;
        Arrays.sort(num);
        res.add(new ArrayList<Integer>());
        
        int start = 0;
        for(int i = 0; i < num.length; i++){
            int size = res.size();
            for(int j = start; j < size; j++){
                List<Integer> sol = new ArrayList<Integer>(res.get(j));
                sol.add(num[i]);
                res.add(sol);
            }
            
            if(i < num.length - 1 && num[i] == num[i + 1])
                start = size;
            else
                start = 0;
        }
        
        return res;
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值