题目:
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) {
res.clear();
memset(used, false, sizeof(used));
sort(num.begin(), num.end());
dfs(0, num.size(), num);
return res;
}
private:
vector<vector<int> > res;
bool used[100];
int a[100];
void dfs(int dep, int maxDep, vector<int> &num) {
if (dep == maxDep) {
vector<int> tt;
for (int i = 0; i < maxDep; i++)
tt.push_back(a[i]);
res.push_back(tt);
return;
}
for (int i = 0; i < maxDep; i++) {
if (!used[i]) {
if (i != 0 && num[i] == num[i - 1] && !used[i - 1])
continue;
used[i] = true;
a[dep] = num[i];
dfs(dep + 1, maxDep, num);
used[i] = false;
}
}
}
};