# Permutations II

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

For example,

[1,1,2] have the following unique permutations:

```
[
[1,1,2],
[1,2,1],
[2,1,1]
]
```

```
public class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
if (nums == null || nums.length == 0) {
return result;
}
Arrays.sort(nums);
boolean[] visited = new boolean[nums.length];
permuteHelper(nums, result, new ArrayList<>(), visited);
return result;
}
void permuteHelper(int[] nums, List<List<Integer>> result, List<Integer> list,
boolean[] visited) {
if (list.size() == nums.length) {
result.add(new ArrayList(list));
return;
}
for (int i = 0; i < nums.length; i++) {
if (visited[i] || (i > 0 && nums[i - 1] == nums[i] && !visited[i - 1])) {
continue;
}
list.add(nums[i]);
visited[i] = true;
permuteHelper(nums, result, list, visited);
list.remove(list.size() - 1);
visited[i] = false;
}
}
}
```

Hope this helps,

Michael