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 mute(vector<vector<int> > &v, vector<int> a, int k, vector<int> &num, vector<bool> b)
{
int n = num.size();
if(k == 0)
{
v.push_back(a);
return;
}
for(int i = 0; i < n; i++)
{
if(b[i] == false)
{
if((i != 0)&&(num[i] == num[i-1])&&(b[i-1])) continue;
a.push_back(num[i]);
b[i] = true;
mute(v,a,k-1,num,b);
b[i] = false;
a.pop_back();
}
}
return;
}
vector<vector<int> > permuteUnique(vector<int> &num) {
vector<vector<int> > v;
int n = num.size();
sort(num.begin(),num.end());
vector<int> a;
vector<bool> IsUsed(n,false);
if(n == 0)return v;
mute(v,a,n,num,IsUsed);
return v;
}
};