Concise Java Recursive Solution


  • 1
    M
    public List<List<Integer>> subsetsWithDup(int[] nums) {
    
    	Arrays.sort(nums);
    	List<List<Integer>> ans = new LinkedList<List<Integer>>();
    	if (nums.length < 1)
    		return ans;
    	subsetsWithDupHelper(ans, nums, new LinkedList<Integer>(), 0);
    
    	return ans;
    
    }
    
    private void subsetsWithDupHelper(List<List<Integer>> ans, int[] nums,
    		LinkedList<Integer> curAns, int start) {
    	ans.add(curAns);
    	if (start == nums.length)
    		return;
    
    	for (int i = start; i < nums.length; i++) {
    		if (i == start || nums[i] != nums[i - 1]) {
    			LinkedList<Integer> newCur = new LinkedList<Integer>(curAns);
    			newCur.add(nums[i]);
    			subsetsWithDupHelper(ans, nums, newCur, i + 1);
    		}
    	}

Log in to reply
 

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