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]
.
Solution:
void cal(vector<int> &num, vector<int>& cur, vector<int>& visited, vector<vector<int> >& result)
{
if(cur.size()==num.size())
{
result.push_back(cur);
return;
}
for(int i=0;i<num.size();i++)
{
if(visited[i]!=1)
{
/* if previous number equal to current one but is not used, we can not use this one. Since If we use, we will use previous number in next round which is duplicated.*/
if(i>0&&num[i]==num[i-1]&&visited[i-1]==0)
continue;
cur.push_back(num[i]);
visited[i] =1;
cal(num, cur, visited, result);
cur.pop_back();
visited[i] =0;
}
}
}
vector<vector<int> > permuteUnique(vector<int> &num) {
vector<vector<int> > result;
int len = num.size();
vector<int> visited(len, 0);
vector<int> cur;
sort(num.begin(),num.end());
cal(num, cur, visited, result);
return result;
}
No comments:
Post a Comment