Easy to understand Java Solution


  • 0
    A
    public List<List<Integer>> permuteUnique(int[] nums) {
    	List<Integer> reminder = new ArrayList<Integer>();
    	for (int n : nums) reminder.add(n);
    	List<List<Integer>> result = new LinkedList<List<Integer>>();
    	permute(new ArrayList<Integer>(), reminder, result);
    	return result;
    }
    
    void permute(List<Integer> permutation, List<Integer> reminder, List<List<Integer>> result) {
    	if (reminder.size() == 0) { result.add(permutation); return; }
    	for (int i = 0; i < reminder.size(); i++) {
    	    if(isLastOccurance(reminder, i)) {
    	        List<Integer> newPermutation = new ArrayList<Integer>();
    		    newPermutation.addAll(permutation);
    		    newPermutation.add(reminder.get(i));
    		    List<Integer> newReminder = new ArrayList<Integer>();
    		    newReminder.addAll(reminder);
    		    newReminder.remove(i);
    		    permute(newPermutation, newReminder, result);   
    	    }
    	}
    }
    
    boolean isLastOccurance(List<Integer> reminder, int index) {
        for(int i = index+1;i<reminder.size();i++)
            if(reminder.get(i) == reminder.get(index)) 
                return false;
       return true;
    }

Log in to reply
 

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