Very simple and easy understood C++ dfs solution


  • 1
    L
    class Solution {
    public:
        int n;
        vector<vector<int>> ret;
        vector<int> ans;
        vector<bool> used;
        void dfs(int dep, vector<int>& nums) {
            if (n == dep) {
                ret.push_back(ans);
                return;
            }
            for (int i = 0; i < n; ++i)
                if (!used[i] && (i == 0 || nums[i] != nums[i - 1] || used[i - 1])) {
                    used[i] = true;
                    ans.push_back(nums[i]);
                    dfs(dep + 1, nums);
                    ans.pop_back();
                    used[i] = false;
                }
        }
        vector<vector<int>> permuteUnique(vector<int>& nums) {
            ret.clear();
            ans.clear();
            n = nums.size();
            used.resize(n, false);
            sort(nums.begin(), nums.end());
            dfs(0, nums);
            return ret;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.