难度:3
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]
.
求全排列,且不能相同、
先排序
对于相同的数,我们规定必须在结果中的顺序和初始时一样
这样当一个数等于之前那个数,且之前那个数没有存在tmp中,则这个数不能取
这样就可以做DFS
class Solution
{
public:
vector<vector<int> > ans;
vector<int>tmp;
vector<bool>flag;
vector<int>a;
int n;
void dfs(int index)
{
if(index == n) {ans.push_back(tmp);return;}
for(int i=0;i<n;i++)
{
if(flag[i]||(i-1>=0&&a[i] == a[i-1]&&!flag[i-1]) ) continue;
tmp.push_back(a[i]);
flag[i]=true;
dfs(index+1);
tmp.pop_back();
flag[i]=false;
}
}
vector<vector<int> >permuteUnique(vector<int> &num)
{
sort(num.begin(),num.end());
ans.clear();
tmp.clear();
a.assign(num.begin(),num.end());
n=num.size();
flag.assign(n,false);
dfs(0);
return ans;
}
};