当前位置:网站首页>Subsets II of leetcode topic analysis

Subsets II of leetcode topic analysis

2022-06-23 08:39:00 ruochen

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,

[]

]

Use binary , There's no need for recursion . For every bit in the binary ,0 Indicates no choice ,1 Express choice . Then there are 2^n In this case .

Use HashSet, It can filter the repetition directly ( Sort the array first , The title also requires each list Non descending order ).

    public List<List<Integer>> subsetsWithDup(int[] nums) {
        if (nums == null) {
            return null;
        }
        if (nums.length == 0) {
            return new ArrayList<List<Integer>>();
        }
        Set<List<Integer>> set = new HashSet<List<Integer>>();
        //  The title requires each list Descending order of right and wrong , So you have to sort from small to large 
        Arrays.sort(nums);
        //  about n position , Yes 2^n In this case 
        for (int i = 0; i < Math.pow(2, nums.length); i++) {
            List<Integer> list = new ArrayList<Integer>();
            int tmp = i;
            //  For each case , Get the binary respectively 1 The number of 
            // 0 It means no choice ,1 For choice 
            for (int j = 0; j < nums.length; j++) {
                int bit = tmp & 1;
                tmp >>= 1;
                if (bit == 1) {
                    list.add(nums[j]);
                }
            }
            set.add(list);
        }
        return new ArrayList<List<Integer>>(set);
    }
原网站

版权声明
本文为[ruochen]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/01/202201102041064219.html