Given a collection of numbers that might contain duplicates, return all possible unique permutations.
For example,
Answer:[1,1,2]
have the following unique permutations:[1,1,2]
, [1,2,1]
, and [2,1,1]
.class Solution {
public:
void DFS(vector<int>& num, int begin, vector<vector<int>> &res, vector<int> subres, vector<bool> &flag){
if(begin == num.size())
{
res.push_back(subres);
return;
}
for (int i = 0; i < num.size(); ++i)
{
if(!flag[i])//当前元素没有被选
{
//如果前面一个元素没有被选,且和当前元素相同则为避免重复则不选这个元素
if (i > 0 && num[i - 1] == num[i] && !flag[i - 1])
continue;
flag[i] = true;
subres.push_back(num[i]);
DFS(num, begin + 1, res, subres, flag);
flag[i] = false;
subres.pop_back();
}
}
}
vector<vector<int> > permuteUnique(vector<int> &num) {
vector<vector<int> > res;
res.clear();
if(num.size() == 0)
return ans;
vector<bool> flag(num.size(), false);
vector<int> subres;
sort(num.begin(), num.end());//一定要先排序
DFS(num, 0, res, subres, flag);
return res;
}
};
No comments:
Post a Comment