Permutations II

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

For example,
[1,1,2] have the following unique permutations:
[1,1,2], [1,2,1], and [2,1,1].


class Solution {
public:
    void visit(vector<int> &nums, int n, int pos, vector<vector<int> > &result)
    {
        if (n == pos)
        {
            result.push_back(nums);
            return;
        }

        for (int i = pos; i < n; i++)
        {
            sort(nums.begin()+pos, nums.end());
            if (i > pos && nums[i] == nums[i-1])
            {
                continue;
            }

            swap(nums[pos], nums[i]);
            visit(nums, n, pos+1, result);
            swap(nums[pos], nums[i]);
        }
    }

    vector<vector<int>> permuteUnique(vector<int>& nums) {
        vector<vector<int> > result;
        int n = nums.size();
        if (n < 1)
        {
            return result;
        }             

        sort(nums.begin(), nums.end());
        visit(nums, n, 0, result);

        return result;
    }
};


你可能感兴趣的:(Permutations II)