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


Consider example [1,2,3] returns

[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,2,1], 
[3,1,2]


This problem is classic example of backtracking. If there is no duplicate element, the total number of elements are n! where n is the number of elements.

public class Permutations {

	public static void main(String[] args) {
		System.out.println(new Permutations().permute(new int[] { 1, 2, 3 }));
	}

	public List<List<Integer>> permute(int[] nums) {
		List<List<Integer>> bigList = new ArrayList<List<Integer>>();
		permute(nums, 0, bigList);
		return bigList;
	}

	private void permute(int[] nums, int index, List<List<Integer>> bigList) {
		if (index == nums.length) {
			List l = new ArrayList(nums.length);
			for (int num : nums)
				l.add(num);
			bigList.add(l);
			return;
		}
		for (int i = index; i < nums.length; i++) {
			swap(nums, i, index);
			permute(nums, index + 1, bigList);
			swap(nums, i, index);
		}
	}

	private void swap(int[] nums, int i, int index) {
		int temp = nums[i];
		nums[i] = nums[index];
		nums[index] = temp;
	}
}	
Check how to handle if the array contains duplicate

Subscribe to get latest updates.

© 2016 Java Questions | Sitemap