码迷,mamicode.com
首页 > 其他好文 > 详细

[Leetcode 90]求含有重复数的子集 Subset II

时间:2018-11-17 23:24:24      阅读:310      评论:0      收藏:0      [点我收藏+]

标签:remove   not   style   with   span   16px   leetcode   etc   str   

【题目】

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);
        }
    }
}

[Leetcode 90]求含有重复数的子集 Subset II

标签:remove   not   style   with   span   16px   leetcode   etc   str   

原文地址:https://www.cnblogs.com/inku/p/9976099.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!