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 & nums, int num, int start, int end) { int i = 0; for (i=start; i
> &res, vector
& 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
> permuteUnique(vector & nums) { sort(nums.begin(), nums.end()); vector > res; int start = 0; int end = nums.size() - 1; _permute(res, nums, start ,end); return res; }};