Permutations II
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]
.
My Code
class Solution {
public:
void doPermute(vector<vector<int> >& res, vector<int> r, vector<int> v)
{
int size = v.size();
if (size == 1)
{
r.push_back(v[0]);
res.push_back(r);
return;
}
unordered_set<int> s;
for (int i = 0; i < size; i++)
{
if (s.find(v[i]) != s.end())
continue;
else
s.insert(v[i]);
vector<int> rr(r);
vector<int> vv(v);
rr.push_back(v[i]);
vv.erase(vv.begin() + i);
doPermute(res, rr, vv);
}
}
vector<vector<int> > permuteUnique(vector<int>& nums) {
vector<vector<int> > res;
vector<int> r;
vector<int> v(nums);
doPermute(res, r, v);
return res;
}
};
Runtime: 48 ms