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],
[2,1,1]
]
思路一:递归,用 set 去重
//63 ms
class Solution {
public:
set <vector<int> > result;
// permute num[begin..end]
// invariant: num[0..begin-1] have been fixed/permuted
void permuteRecursive(vector<int> &num, int begin, set<vector<int> > &result)
{
if (begin >= num.size()) {
// one permutation instance
result.insert(num);
return;
}
for (int i = begin; i < num.size(); i++) {
swap(num[begin], num[i]);
permuteRecursive(num, begin + 1, result);
// reset
swap(num[begin], num[i]);
}
}
vector<vector<int> > permuteUnique(vector<int> &num)
{
vector<vector<int> > res;
permuteRecursive(num, 0, result);
set<vector<int> >::iterator it = result.begin();
while(it != result.end())
{
res.push_back(*it);
it++;
}
return res;
}
};
思路二:递归,不相同的元素可以交换
//22 ms
class Solution {
public:
void recursion(vector<int> num, int i, int j, vector<vector<int> > &res) {
if (i == j-1) {
res.push_back(num);
return;
}
for (int k = i; k < j; k++) {
if (i != k && num[i] == num[k]) continue;
swap(num[i], num[k]);
recursion(num, i+1, j, res);
}
}
vector<vector<int> > permuteUnique(vector<int> &num) {
sort(num.begin(), num.end());
vector<vector<int> >res;
recursion(num, 0, num.size(), res);
return res;
}
};