**Input:** nums = [1,1,2]
**Output:**
[[1,1,2],
[1,2,1],
[2,1,1]]
**Input:** nums = [1,2,3]
**Output:** [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
Arrays.sort(nums);
backtrack(nums, res, new ArrayList<Integer>(), new boolean[nums.length]);
return res;
}
private void backtrack(int[] nums, List<List<Integer>> res, List<Integer> note, boolean[] visiting) {
// exit, all elements are included
if (note.size() == nums.length) {
res.add(new ArrayList<Integer>(note));
return;
}
for (int i = 0; i < nums.length; i++) {
if (visiting[i] || i > 0 && nums[i] == nums[i-1] && !visiting[i-1]) continue; // skip duplicate
note.add(nums[i]);
visiting[i] = true;
backtrack(nums, res, note, visiting);
visiting[i] = false;
note.remove(note.size()-1);
}
}
}