import java.util.*;

public class Solution {
    public ArrayList<ArrayList<Integer>> permuteUnique(int[] num) {
        ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
        Arrays.sort(num);
        boolean[] isVisited = new boolean[num.length];
        int length = num.length;
        DFS(num, isVisited, ans, new ArrayList<>(), length);
        return ans;
    }
    public void DFS(int[] num, boolean[] isVisited,
                    ArrayList<ArrayList<Integer>> ans, ArrayList<Integer> temp, int length) {
        if (length == 0 && !ans.contains(temp)) {
            ans.add(new ArrayList<>(temp));
            return;
        } else {
            for (int i = 0; i < num.length; i++) {
                if (!isVisited[i]) {
                    isVisited[i] = true;
                    temp.add(num[i]);
                    DFS(num, isVisited, ans, temp, length - 1);
                    temp.remove(temp.size() - 1);
                    isVisited[i] = false;
                }
            }
        }
    }
}