Short and clean Java solution


  • 0
    J
     public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> ans = new ArrayList<>();
        Arrays.sort(nums);
        permutating(ans, nums, 0);
        return ans;
    }
    
    private void permutating(List<List<Integer>> ans, int[] nums, int start) {
    	if (start == nums.length - 1) {
    		List<Integer> li = new ArrayList<>();
    		for (int n : nums) {
    			li.add(n);
    		}
    		ans.add(li);
    		return;
    	}
    	for (int i = start; i < nums.length; i++) {
    		if (i != start && nums[start] == nums[i]) {
    			continue;
    		}
    		swap(nums, start, i);
    		permutating(ans, Arrays.copyOf(nums, nums.length), start+1);
    	}
    }
    
    private void swap(int[] nums, int i, int j) {
    	int temp = nums[i];
    	nums[i] = nums[j];
    	nums[j] = temp;
    }

  • 0
    M

    Hi, thanks for sharing this solution! I am still wondering though - why we need to do the sorting first to make it works?


Log in to reply
 

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