Java Solution


  • 0
    M

    Solution : The basic idea is that every element is either added 1 or not 0 to the set. The total number of elements added to he set are 2^n. Calculate binary string representation to see what numbers are needed to be added to the list.
    ...

    public List<List<Integer>> subsetsWithDup(int[] nums) {
    	Set<List<Integer>> result = new HashSet<List<Integer>>();
    	List<List<Integer>> resultList = new ArrayList<List<Integer>>();
    	int size = (Integer.toBinaryString((int)Math.pow(2, nums.length))).length()-1;
    	for(int i=0;i<(Math.pow(2, nums.length));i++){
    		StringBuilder binaryStr = new StringBuilder(Integer.toBinaryString(i));
    		for(int k=binaryStr.length();k<size;k++){
    			binaryStr=binaryStr.insert(0,"0");
    		}
    		List<Integer> set = new ArrayList<Integer>();
    		for(int j=0;j<binaryStr.length();j++){
    			if(binaryStr.charAt(j)=='1'){
    				set.add(nums[j]);
    			}
    		}
    		Collections.sort(set);
    		result.add(set);
    	}
    	for(List<Integer> s:result){
    		resultList.add(new ArrayList<Integer>(s));
    	}
    	return resultList;
    }
    

    ...


Log in to reply
 

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