Permutations II
Given a list of numbers with duplicate number in it. Find all unique permutations.
Example:
For numbers [1,2,2] the unique permutations are:
[
[1,2,2],
[2,1,2],
[2,2,1]
]
Code:
class Solution {
/**
* @param nums: A list of integers.
* @return: A list of unique permutations.
*/
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if (nums == null || nums.length == 0) {
res.add(new ArrayList<Integer>());
return res;
}
Arrays.sort(nums);
List<Integer> perm = new ArrayList<>();
Set<Integer> visited = new HashSet<>();
dfs(nums, perm, visited, res);
return res;
}
private void dfs(int[] nums, List<Integer> perm, Set<Integer> visited,
List<List<Integer>> res) {
if (perm.size() == nums.length) {
res.add(new ArrayList<>(perm));
return;
}
int prev = Integer.MIN_VALUE; // use to remove the duplicated solution in res
for (int i = 0; i < nums.length; i++) {
if (visited.contains(i) || prev == nums[i]) {
continue;
}
perm.add(nums[i]);
visited.add(i);
dfs(nums,perm, visited, res);
perm.remove(perm.size() - 1);
visited.remove(i);
prev = nums[i];
}
}
}