[Leetcode 90]求含有重复数的子集 Subset 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.

【思路】

注意sort,使得判断临接元素是否相邻。

与leetcode78类似,多了一个重复数判断条件

            if(i>flag&&nums[i-1]==nums[i])
                continue;

【代码】

public class Solution {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        List<List<Integer>> ans=new ArrayList<>();
        List<Integer> tmp=new ArrayList<>();
        Arrays.sort(nums);
        fun(nums,ans,tmp,0);
        return ans;
    }
    
    public void fun(int nums[],List<List<Integer>> ans,List<Integer> tmp,int flag){
        ans.add(new ArrayList<>(tmp));
        for(int i=flag;i<nums.length;i++){
            if(i>flag&&nums[i-1]==nums[i])
                continue;
            tmp.add(nums[i]);
            fun(nums,ans,tmp,i+1);
            tmp.remove(tmp.size()-1);
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/inku/p/9976099.html