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 DFS(vector<vector<int> > &ans, vector<int> &vec, int n, int step)
{
if (step == n)
{
ans.push_back(vec);
return;
}
for (int i = step; i < n; ++i)
{
bool bSwap = true;
for (int j = step; j < i; ++j)
{
if (vec[j] == vec[i])
{
bSwap = false;
break;
}
}
if (!bSwap)
{
continue;
}
swap(vec[i], vec[step]);
DFS(ans, vec, n, step + 1);
swap(vec[i], vec[step]);
}
}
vector<vector<int> > permuteUnique(vector<int> &num) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<vector<int> > ans;
int size = num.size();
DFS(ans, num, size, 0);
return ans;
}
};