Given a collection of numbers that might contain duplicates, return all possible unique permutations.
[
[1,1,2],
[1,2,1],
[2,1,1]
]
class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> permutation = new ArrayList<>();
boolean[] used = new boolean[nums.length];
Arrays.sort(nums);
getPermutation(nums, used, permutation, res);
return res;
}
public void getPermutation(int[] nums, boolean[] used, List<Integer> permutation, List<List<Integer>> res) {
if (permutation.size() == nums.length) {
res.add(new ArrayList<>(permutation));
return;
}
for (int i = 0; i < nums.length; i++) {
if (i > 0 && nums[i - 1] == nums[i] && !used[i - 1]) {
continue;
}
if (!used[i]) {
used[i] = true;
permutation.add(nums[i]);
getPermutation(nums, used, permutation, res);
permutation.remove(permutation.size() - 1);
used[i] = false;
}
}
}
}
3. Time & Space Complexity