import java.util.*;
public class Solution {
public ArrayList<ArrayList<Integer>> permuteUnique(int[] num) {
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
boolean[] visited = new boolean[num.length];
Arrays.sort(num);
dfs(res, num, new ArrayList<>(), visited);
return res;
}
private void dfs(ArrayList<ArrayList<Integer>> res, int[] num, ArrayList<Integer> list, boolean[] visited){
if (list.size() == num.length){
res.add(new ArrayList<>(list));
return;
}
for (int i = 0; i < num.length; i++){
if (visited[i]) continue;
if (i > 0 && num[i] == num[i - 1] && visited[i - 1]) continue;
visited[i] = true;
list.add(num[i]);
dfs(res, num, list, visited);
visited[i] = false;
list.remove(list.size() - 1);
}
}
}