# 90 Subsets II

Description

Given an integer array nums that may contain duplicates, return all possible subsets (the power set).

The solution set must not contain duplicate subsets. Return the solution in any order.

Examples

Example 1:

Input: nums = [1,2,2]
Output: [[],[1],[1,2],[1,2,2],[2],[2,2]]

Example 2:

Input: nums = [0]
Output: [[],[0]]

Constraints:

1 <= nums.length <= 10
-10 <= nums[i] <= 10

思路1及对应代码

最开始的时候是用 #78 subsets 里面的思路2,但是因为有重复数据,所以要用Set做存储,最后转为List即可

class Solution {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        Set<List<Integer>> toAdd = new HashSet<>();
        Set<List<Integer>> answer = new HashSet<>();
        Arrays.sort(nums);
        
        toAdd.add(new ArrayList<>());
        answer.add(new ArrayList<>());
        for(int i = 0; i < nums.length; i++){
            for(List<Integer> temp: toAdd){
                List<Integer> t = new ArrayList<>(temp);
                t.add(nums[i]);
                answer.add(new ArrayList<>(t));
            }
            toAdd.addAll(answer);
        }
        
        return new ArrayList<>(answer);
    }
}

思路2及对应代码

思路2在于处理重复数据的方式,也就不用Set进行数据存储,而是通过先对重复数据进行处理的方法

class Solution {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        List<List<Integer>> answer = new ArrayList<>();
        
        Arrays.sort(nums);
        answer.add(new ArrayList<>());
        
        for(int i = 0; i < nums.length; i++){
            int count = 1;
            while(i < nums.length - 1 && nums[i] == nums[i + 1]){
                count ++;
                i++;
            }
            int s = answer.size();
            for(int n = 0; n < s; n++){
                List<Integer> t = new ArrayList<>(answer.get(n));
                for(int j = 0; j < count; j++){
                    t.add(nums[i]);
                    answer.add(new ArrayList<>(t));
                }
            }
        }
        
        return answer;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值