My two clean methods (cpp)


  • 0
    C

    STL:

    class Solution {
    public:
        vector<vector<int>> permuteUnique(vector<int>& nums) 
        {
            std::sort(nums.begin(), nums.end());
            
            vector< vector<int> > result;
            result.push_back(nums);
    
            vector<int> p(nums);
            while( std::next_permutation(p.begin(), p.end()) )
                result.push_back( vector<int>(p) );
    
            return result;
        }
    };
    

    Recursive:

    class Solution {
    public:
    
        vector< vector<int> > result;
    
        void helper(const vector<int> &nums, vector<bool> &isVisited, vector<int> &res)
        {
            if(res.size() == nums.size())
            {
                result.push_back( vector<int>(res) );
                return;
            }
            
            for(int i=0; i < isVisited.size();)
            {
                if(isVisited[i]) 
                {
                    i++;
                    continue;
                }
                
                isVisited[i] = true;
                
                int cur = nums[i];
                
                res.push_back(cur);
                helper(nums, isVisited, res);
                res.pop_back();
                
                isVisited[i] = false;
                
                while(i < nums.size() && nums[i] == cur)
                    i++;
            }
        }
    
        vector<vector<int>> permuteUnique(vector<int>& nums) 
        {
            std::sort(nums.begin(), nums.end());
            
            vector<bool> isVisited(nums.size(), false);
            vector<int> res;
            
            helper(nums, isVisited, res);
            
            return result;
        }
    };

  • 0
    5

    it's cheating if you use the function next_permutation of STL


  • 0
    B

    Of course, but it's still a kind of solution.


Log in to reply
 

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