class Solution {
public:
    void dfs(vector<int> &num, vector<vector<int>> &res, vector<int> &ans, vector<bool>& flag) {
        if(ans.size() == num.size()) {
            if(!count(res.begin(), res.end(), ans))
                res.push_back(ans);
        }
        for(int i = 0; i < num.size(); i++) {
            if(!flag[i]) {
                ans.push_back(num[i]);
                flag[i] = 1;
                dfs(num, res, ans, flag);
                ans.pop_back();
                flag[i] = 0;
            }
        }
    }
    vector<vector<int> > permuteUnique(vector<int> &num) {
        sort(num.begin(), num.end());
        vector<vector<int> > res;
        vector<int> ans;
        vector<bool> flag(num.size(), false);
        dfs(num, res, ans, flag);
        return res;
    }
};