C++ solution adapted from the most voted Permutations I solution of mine


  • 3
    X
    class Solution {
    public:
        vector<vector<int> > permuteUnique(vector<int> &num) {
            vector<vector<int> > result;
            
            permuteRecursive(num, 0, result);
            return result;
        }
     
        void permuteRecursive(vector<int> &num, int begin, vector<vector<int> > &result)    {
            if (begin >= num.size()) {
                result.push_back(num);
                return;
            }
            
            // detect duplicate        
            unordered_set<int> set;
            for (int i = begin; i < num.size(); i++) {
                if (set.count(num[i]) > 0)
                    continue;
                set.insert(num[i]);
                
                swap(num[begin], num[i]);
                permuteRecursive(num, begin + 1, result);
                swap(num[begin], num[i]);
            }
        }
    };

Log in to reply
 

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