LeetCode 90: Subsets II

问题描述

Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

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

java实现

class Solution {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        List<List<Integer>> results=new ArrayList<>();
        if(nums==null || nums.length==0){
            return results;
        }

        Arrays.sort(nums);

        //递归搜索
        List<Integer> subset=new ArrayList<Integer>();
        subsutHelper(nums,0,subset,results);
        return results;

    }
    private void subsutHelper(int[] nums , int startIndex, List<Integer> subset ,List<List<Integer>> results){
        //深度拷贝 以及 加入结果数组
        results.add(new ArrayList<Integer>(subset));
        for (int i = startIndex; i <nums.length ; i++) {
            /*因为排序过 相等的数在一起  可以用nums[i]==nums[i-1]判断nums[i]是否已经存在

            i-1位置的数进入subset,下一个进入的是i-1+1=i位置的数
            (上次挑选的数字是startIndex-1,这次挑选的是i>=startIndex+1,中间至少有一个数,说明i-1位置的数没有放到subset中,但是
            却和i位置的数相等,说明出现挑选第二个2却没有挑选第一个2的情况。我们的选择原则是选择最先出现的
            
            注意下标越界的问题i-1有可能越界,所以加上判断i!=0
            */
            
            if(i!=0 && nums[i]==nums[i-1] && i>startIndex)
                continue;

            subset.add(nums[i]);
            subsutHelper(nums,i+1,subset,results);
            subset.remove(subset.size()-1);
        }
    }
}
发布了172 篇原创文章 · 获赞 22 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_44135282/article/details/103395878
今日推荐