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 _swap (int &a, int &b) {
        int tmp = a;
        a = b;
        b = tmp;
    }
    bool exist(vector<int>& nums, int num, int start, int end) {
        int i = 0;
        for (i=start; i<end; i++) {
            if (nums[i] == num) {
                return true;
            }
        }
        return false;
    }
    void _permute(vector<vector<int>> &res, vector<int>& nums, int start, int end) {

        if (start >= end) {
            res.push_back(nums);
            return;
        }
        int i;
        for (i=start; i<=end; i++) {
            if (exist(nums, nums[i], start, i)) {
                continue;
            }
            _swap(nums[start], nums[i]);
            _permute(res, nums, start+1, end);
            _swap(nums[start], nums[i]);
        }
    }
    vector<vector<int>> permuteUnique(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        vector<vector<int>> res;
        int start = 0;
        int end = nums.size() - 1;
        _permute(res, nums, start ,end);
        return res;
    }
};

 

posted on 2016-02-07 17:44  walkwalkwalk  阅读(190)  评论(0编辑  收藏  举报

导航