Simple solution using c++


  • -1
    X
    class Solution {
    public:
        vector<vector<int> > permuteUnique(vector<int> &num) {
            vector<vector<int> > res;
            if (0 == num.size()) return res;
            sort(num.begin(), num.end());
            res.push_back(num);
            int gap, tobeswap;
            while (1) {
                for (gap = num.size() - 2; gap >= 0 && num[gap] >= num[gap + 1]; --gap);
                if (-1 == gap) break;
                for (tobeswap = num.size() - 1; num[tobeswap] <= num[gap]; --tobeswap);
                swap(num[gap], num[tobeswap]);
                sort(num.begin() + gap + 1, num.end());
                res.push_back(num);
            }
            return res;
        }
    };
    

    using the same idea as next_permutation in <algorithm>,generate all the permutation by lexicographical order.


Log in to reply
 

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