38 ms c++ solution using set


  • 3
    P
    vector<vector<int> > permuteUnique(vector<int> &num) {
            vector<vector<int> > result;
            int n = num.size();
            if (n > 0) {
                helper(num, 0, n, result);
            }
            return result;
        }
        
        void helper(vector<int>& a, int pos, int n, vector<vector<int> >& result) {
            if (pos == n-1) {
                result.push_back(a);
                return;
            }
            
            unordered_set<int> swapped;
            for (int i = pos; i < n; ++i) {
                if (swapped.find(a[i]) != swapped.end()) continue;
                swapped.insert(a[i]);
                swap(a[pos], a[i]);
                helper(a, pos+1, n, result);
                swap(a[pos], a[i]);
            }
        }

  • 0
    H

    what's mean swap(a[pos], a[i]); ??


  • 0
    P

    it swaps the elements at a[pos],a[i]
    http://en.cppreference.com/w/cpp/algorithm/swap


Log in to reply
 

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