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