AC java solution using HashSet


  • 0
    U
    public class Solution { // only difference with subset I is here i added a hashset
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> res1= new ArrayList<List<Integer>>();// for returning a list
        HashSet<List<Integer>> res = new HashSet<List<Integer>>();
        for(int i=0;i<=nums.length;i++){
            helper(nums, res, new ArrayList<Integer>(),i, 0);
        }
        res1.addAll(res); // convert set to list
        return res1;
        
    }
    private void helper(int[] nums, HashSet<List<Integer>> res,List<Integer> each,int number, int index){
        if(each.size()==number&&!res.contains(each)){
            res.add(new ArrayList(each));
            return;
        } 
        
        for(int j=index;j<nums.length;j++){
            each.add(nums[j]);
            helper(nums,res,each,number,j+1);
            each.remove(each.size()-1);
        }
        
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.