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]
.
先排序,如果一个元素与上一个元素相等,且前面没有使用该元素,则该元素不参与当前排列
class Solution {
public:
vector<vector<int> > permuteUnique(vector<int> &num) { sort(num.begin(),num.end());
vector<vector<int> > result;
vector<int> tmp;
vector<bool> visited(num.size());
dfs(,num,result,visited,tmp);
return result; } void dfs(int level,vector<int> &num,vector<vector<int> > &result,vector<bool> &visited,vector<int> &tmp)
{
if(level==num.size())
{
result.push_back(tmp);
return;
} for(int i=;i<num.size();i++)
{
if(!visited[i])
{
if(i>=&&((num[i]==num[i-]&&visited[i-])||(num[i]!=num[i-]))||i==)
{
visited[i]=true;
tmp.push_back(num[i]);
dfs(level+,num,result,visited,tmp);
tmp.pop_back();
visited[i]=false;
}
}
}
} };