47. Permutations II (Medium)
https://leetcode.com/problems/permutations-ii/
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
Example:
Input: [1,1,2] Output: [ [1,1,2], [1,2,1], [2,1,1] ]
Solutions
1.
class Solution {
Set<String> uniqueHash = new HashSet<>();
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> ans = new ArrayList<>();
if (nums == null || nums.length == 0) {
return ans;
}
Arrays.sort(nums);
doPermutation(nums, ans, 0);
return ans;
}
private void doPermutation(int[] nums, List<List<Integer>> ans, int depth) {
int len = nums.length;
if (depth == len - 1) {
List<Integer> solution = new ArrayList<>();
for (int n : nums) {
solution.add(n);
}
if (uniqueHash.add(solution.toString())) {
ans.add(solution);
}
return;
}
for (int j = depth; j < len; j++) {
// pruning
if (j != depth && nums[j] == nums[depth]) {
continue;
}
swap(nums, depth, j);
doPermutation(nums, ans, depth + 1);
swap(nums, depth, j);
}
}
void swap(int[] nums, int x, int y) {
int tmp = nums[x];
nums[x] = nums[y];
nums[y] = tmp;
}
}
2.
class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> ans = new ArrayList<>();
Arrays.sort(nums);
doPermutation(nums, ans, 0);
return ans;
}
void doPermutation(int[] nums, List<List<Integer>> ans, int depth) {
if (depth == nums.length - 1) {
List<Integer> list = new ArrayList<>();
for (int n : nums) {
list.add(n);
}
ans.add(list);
return;
}
// From the perspective how you do permutation, first slot has len situations.
// But the problem also points out the duplicate element issue, so the number of situations
// is the count of unique element.
// For elements already swapped, ignore it. Here we use a set to track the swapped value.
Set<Integer> swaped = new HashSet<>();
for (int j = depth, l = nums.length; j < l; j++) {
if (!swaped.add(nums[j])) {
continue;
}
// Above commented out code is not correct, should not be executed
/*
if (depth != 0 && nums[depth] == nums[depth-1]) {
continue;
}
if (j != depth && nums[j] == nums[depth]) {
continue;
}
if (j != depth && nums[j] == nums[j-1]) {
continue;
}
*/
swap(nums, depth, j);
doPermutation(Arrays.copyOf(nums, nums.length), ans, depth + 1);
swap(nums, depth, j);
}
}
void swap(int[] a, int i, int j) {
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}