Permutations II

来源:互联网 发布:sql select 结果 左链 编辑:程序博客网 时间:2024/06/09 00:26

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;    }};


0 0