Given a set of integers, return all possible permutations that contains duplicate.


Consider example [1,2,2] returns

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


This problem is classic example of backtracking. If there are duplicate elements, the total number of elements are n!/(k!z!) where n is the total number of elements and k,z are duplicate count for an integer.

public class Permutations {

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

	public List<List<Integer>> permuteUnique(int[] nums) {
		List<List<Integer>> bigList = 
			new ArrayList<List<Integer>>();
		Arrays.sort(nums);
		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<Integer>(nums.length);
			for (int num : nums)
				l.add(num);
			bigList.add(l);
			return;
		}
		Set<Integer> dups = new HashSet();
		for (int i = index; i < nums.length; i++) {
			if (dups.add(nums[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;
	}
}	

Subscribe to get latest updates.

© 2016 Java Questions | Sitemap