import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class PermutationsWithDuplicates {
public static List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums);
boolean[] used = new boolean[nums.length];
List<Integer> currentPermutation = new ArrayList<>();
generatePermutations(nums, used, currentPermutation, result);
return result;
}
private static void generatePermutations(int[] nums, boolean[] used, List<Integer> currentPermutation, List<List<Integer>> result) {
if (currentPermutation.size() == nums.length) {
result.add(new ArrayList<>(currentPermutation));
return;
}
for (int i = 0; i < nums.length; i++) {
if (used[i] || (i > 0 && nums[i] == nums[i - 1] && !used[i - 1])) {
continue;
}
used[i] = true;
currentPermutation.add(nums[i]);
generatePermutations(nums, used, currentPermutation, result);
used[i] = false;
currentPermutation.remove(currentPermutation.size() - 1);
}
}
public static void main(String[] args) {
int[] nums = {1, 1, 2};
List<List<Integer>> permutations = permuteUnique(nums);
for (List<Integer> permutation : permutations) {
System.out.println(permutation);
}
}
}