My 36ms C++ solution


  • -1
    T
    class Solution {
    public:
        vector<vector<int>> permuteUnique(vector<int>& nums) {
            int n = nums.size();
            
            vector<int> temp;
            temp.resize(n);
            
            vector< vector<int> > result;
            
            vector<int> index;
            index.resize(n, 0);
            
            sort(nums.begin(), nums.end());
            int i, current=0;
            for(i=1; i<n; i++)
            {
                if(nums[i] == nums[i-1])
                    index[i] = current;
                else
                {
                    current = i;
                    index[i] = current;
                }
            }
            
            do
            {
                for(i=0; i<n; i++)
                {
                    temp[i] = nums[index[i]];
                }
                result.push_back(temp);
            } while(next_permutation(index.begin(), index.end()));
            
            return result;
        }
    };

  • -1
    R

    If you are going to use std::next_permutation, even this would do:

    vector<vector<int>> permute(vector<int>& nums) {
            vector<vector<int>> result;
            sort(nums.begin(),nums.end());
            do
            {
                result.push_back(nums);
            }while(std::next_permutation(nums.begin(),nums.end()));
            return result;
    }

Log in to reply
 

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