Answer:
vector<vector<int> > permuteUnique(vector<int> &num) {
vector<vector<int> > res;
perm(num, 0, (num.size()-1), res);
return res;
}
void perm(vector<int> num,int k,int n, vector<vector<int> > &res){
if (k==n){
res.push_back(num);
return;
}
else{
unordered_set<int> used;
for (int i=k;i<=n;i++){
//avoid swap with same element in same level!!!
if(used.count(num[i]))continue;
else{
used.insert(num[i]);
//swap(num[k], num[i])
int tmp = num[k];
num[k]=num[i];
num[i]=tmp;
//k+1!!!
perm(num, k+1, n, res);
//swap(num[k], num[i])
tmp = num[k];
num[k]=num[i];
num[i]=tmp;
}
}
}
}
No comments:
Post a Comment