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 permuteUniqueInternal(vector<int> num, int index, vector<int>& currecord, vector<vector<int>> &results) {
if(index == num.size()) {
results.push_back(currecord);
}
else {
for(int ii = index; ii < num.size(); ii ++) {
if(ii > index && num[ii] == num[index]) { // Do not process the same number
continue;
}
swap(num[index], num[ii]);
currecord.push_back(num[index]);
permuteUniqueInternal(num, index + 1, currecord, results);
currecord.pop_back();
}
//sort(num.begin() + index, num.end());
}
}
vector<vector<int> > permuteUnique(vector<int> &num) {
vector<vector<int> > results;
vector<int> currentrecord;
sort(num.begin(), num.end());
permuteUniqueInternal(num, 0, currentrecord, results);
return results;
}
};
class Solution {
public:
bool find(vector<int> &num, int start, int end, int target)
{
for(int i = start; i < end; i++)
if(num[i] == target)
return true;
return false;
}
void findAllPermute(vector<int> &num, int index, vector<int> result, vector<vector<int> >& results)
{
if (num.size() == index)
{
results.push_back(result);
return;
}
for (int ii = index; ii < num.size() ; ii ++)
{
if(ii == index || !find(num, index, ii, num[ii]))
{
swap(num[index], num[ii]);
result.push_back(num[index]);
findAllPermute(num, index + 1, result, results);
result.pop_back();
swap(num[index], num[ii]);
}
}
}
vector<vector<int> > permuteUnique(vector<int> &num) {
vector<vector<int> > results;
vector<int> result;
findAllPermute(num, 0, result, results);
return results;
}
};