What if the given array is non distinct integers?


  • 0
    M

    Is there an efficient way to remove the duplicate before adding it into the list?
    Thanks for giving some ideas.


  • 2
    M

    Here is my solution:

    public static List<List<Integer>> subsets2(int[] nums) {
    	List<List<Integer>> result = new ArrayList<List<Integer>>();
    	List<Integer> item = new ArrayList<Integer>();
        // add empty set
    	result.add(item); 
    
    	Arrays.sort(nums);
    
    	int repeat = 0;
    
    	for (int i = 0; i < nums.length; i++) {
    		int n = result.size();
    		if (i > 0 && nums[i] == nums[i - 1]) {
    			repeat++;
    		} else {
    			repeat = 0;
    		}
    		for (int j = repeat; j < n; j++) {
    			item = new ArrayList<Integer>(result.get(j));
    			item.add(nums[i]);
    			result.add(item);
    		}
    	}
    	return result;
    }

Log in to reply
 

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