Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
39 lines (35 sloc) 1.07 KB
problem:
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 permuteUnique_aux(int index, vector<int>&num, vector<int>&tmp, vector<vector<int> >&ret, vector<bool>&isVisited)
{
if(index == num.size())
{
ret.push_back(tmp);
return;
}
for(int i = 0; i < num.size(); ++i)
{
if(isVisited[i] || (i != 0 && num[i] == num[i - 1] && isVisited[i - 1]))continue;
isVisited[i] = true;
tmp.push_back(num[i]);
permuteUnique_aux(index + 1, num, tmp, ret, isVisited);
isVisited[i] = false;
tmp.pop_back();
}
}
vector<vector<int> > permuteUnique(vector<int> &num)
{
vector<vector<int> > ret;
if(num.size() == 0)
return ret;
sort(num.begin(), num.end());
vector<bool> isVisited(num.size(), false);
vector<int> tmp;
permuteUnique_aux(0, num, tmp, ret, isVisited);
return ret;
}