Using hashmap easy method


  • 2
    N
     public List<List<Integer>> permuteUnique(int[] nums) {
    	HashMap<Integer, Integer> map = new HashMap();
    	for (int i = 0; i < nums.length; i++) {
    		if (map.containsKey(nums[i])) {
    			map.put(nums[i], map.get(nums[i]) + 1);
    		} else {
    			map.put(nums[i], 1);
    		}
    	}
    	List<List<Integer>> ret = new ArrayList();
    	helper(ret, map, new ArrayList(), nums.length);
    	return ret;
    }
    
    public void helper(List<List<Integer>> ret, HashMap<Integer, Integer> map,
    		List<Integer> prefix, int total) {
    	if (prefix.size() == total) {
    		ret.add(new ArrayList(prefix));
    		return;
    	}
    	for (Entry<Integer, Integer> entry : map.entrySet()) {
    		int key = entry.getKey();
    		int value = entry.getValue();
    		if (value > 0) {
    			prefix.add(key);
    			map.put(key, value - 1);
    			helper(ret, map, prefix, total);
    			map.put(key, value);
    			prefix.remove(prefix.size() - 1);
    		}
    	}
    }

Log in to reply
 

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