题目:
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]
.
思路:
与
http://blog.csdn.net/lanxu_yy/article/details/17525459的思路有一些细微的区别。每次取出一个不同的数,然后利用剩下的数形成子集。
代码:
class Solution {
public:
vector<vector<int> > permuteUnique(vector<int> &num) {
sort(num.begin(),num.end());
return generatePermute(num);
}
vector<vector<int>> generatePermute(vector<int> num)
{
vector<vector<int>> results;
if(num.size()==1)
{
vector<int> tmp;
tmp.push_back(num[0]);
results.push_back(tmp);
return results;
}
else
{
int pre=INT_MIN;
int cur=num[0];
int i=0;
do
{
cur = num[i];
if(cur!=pre)
{
num.erase(num.begin()+i);
vector<vector<int>> r = generatePermute(num);
for(int k=0;k<r.size();k++)
{
r[k].insert(r[k].begin(),cur);
results.push_back(r[k]);
}
num.insert(num.begin()+i,cur);
}
pre = cur;
i++;
}
while(i<num.size());
return results;
}
}
};