Clean Java BackTrack Solution


  • 0
    A
    public List<List<Integer>> permute(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++) {
    		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);
    	}
    }

Log in to reply
 

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