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) {
sort(num.begin(), num.end());
vector<int> temp;
vector<int> visited(num.size(), 0);
dfs(num, 0, temp, visited);
return result;
}
private:
vector<vector<int> > result;
void dfs(vector<int> &num, int index, vector<int> &cur, vector<int> &visited)
{
if(index == num.size())
{
result.push_back(cur);
}
else
{
for(int i = 0; i < num.size(); i++)
{
if(visited[i] == 1 || (i > 0 && num[i] == num[i-1] && visited[i-1] == 0))
continue;
else
{
cur.push_back(num[i]);
visited[i] = 1;
dfs(num, index+1, cur, visited);
cur.pop_back();
visited[i] = 0;
}
}
}
}
};
Round 2:
class Solution {
public:
vector<vector<int> > permuteUnique(vector<int> &num) {
std::sort(num.begin(), num.end());
vector<vector<int> > result;
vector<int> cur;
dfs(num, result, cur, 0);
return result;
}
private:
void dfs(vector<int> &num, vector<vector<int> > &result, vector<int> cur, int index)
{
if(num.empty())
{
result.push_back(cur);
return;
}
for(int i = 0; i < num.size(); i++)
{
if(i > 0 && num[i] == num[i-1])
continue;
cur.push_back(num[i]);
num.erase(num.begin() + i);
dfs(num, result, cur, index+1);
num.insert(num.begin()+i, cur.back());
cur.pop_back();
}
}
};