Permutations

LeetCode Q 46 - Permutations

Given a collection of distinct integers, return all possible permutations.

Example:
Input: [1,2,3]
Output:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]

Solution : Backtracking

Code:

private List<List<Integer>> res;
public List<List<Integer>> permute(int[] nums) {
	res = new ArrayList<>();
	if (nums == null || nums.length == 0) return res;
	backtrack(nums, new ArrayList<>());
	return res;
}

private void backtrack(int[] nums, List<Integer> temp) {
	if (temp.size() == nums.length) {
        res.add(new ArrayList(temp)); return;
	}
    
	for (int i = 0; i < nums.length; i++) {
		if (!temp.contains(nums[i])) {
			temp.add(nums[i]);
			backtrack(nums, temp);
			temp.remove(temp.size() - 1);
		}
	}
}

   Reprint policy


《Permutations》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC