C++ 28 ms solution by DFS


  • 0
    T
        vector<vector<int>> permuteUnique(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        
        vector<vector<int>> result;
        dfs(nums, 0, result);
        return result;
    }
    
    void dfs(vector<int>& nums, int begin, vector<vector<int>>& result)
    {
        if (begin == nums.size()-1)
        {
            result.push_back(nums);
            return;
        }
        
        /* set<int> visited; */
        for (int i = begin; i < nums.size(); i++)
        {
            /*
            if (visited.find(nums[i]) != visited.end())
                continue;
            else
                visited.insert(nums[i]);
            */
            bool flag = false;
            for (int j = begin; j < i; j++)
            {
                if (nums[j] == nums[i])
                {
                    flag = true;
                    break;
                }
            }
            
            if (flag)
                continue;
                
            swap(nums[i], nums[begin]);
            dfs(nums, begin+1, result);
            swap(nums[i], nums[begin]);
        }
    }

Log in to reply
 

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