Easy solution using hashSet


  • 0
    U
    public class Solution {
    public List<List<Integer>> combinationSum2(int[] nums, int target) {
        Arrays.sort(nums);
        List<List<Integer>> res1= new ArrayList<List<Integer>>();// for returning a list
        HashSet<List<Integer>> res = new HashSet<List<Integer>>();
        helper(nums, res, new ArrayList<Integer>(),target, 0);
        res1.addAll(res); // convert set to list
        return res1;
    
    }
    private void helper(int[] nums, HashSet<List<Integer>> res,List<Integer> each,int target, int index){
        if(target==0&&!res.contains(each)){
            res.add(new ArrayList(each));
            return;
        } 
    
        for(int j=index;j<nums.length&&nums[j]<=target;j++){// if we dont add nums[j]<=target, we got TLE
            each.add(nums[j]);
            helper(nums,res,each,target-nums[j],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.