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:
vector<vector<int> > permuteUnique(vector<int> &num) {
vector<vector<int> > ret;
Helper(ret, num, 0);
return ret;
}
void Helper(vector<vector<int> >& ret, vector<int> num, int pos)
{
if(pos == num.size()-1)
ret.push_back(num);
else
{
sort(num.begin()+pos, num.end());
for(int i = pos; i < num.size(); i ++)
{
if(i != pos && num[i] == num[i-1])
continue;
swap(num[pos], num[i]);
Helper(ret, num, pos+1);
swap(num[pos], num[i]);
}
}
}
};