[LeetCode]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: void DFS(vector<vector<int> > &res,vector<int> &ans,vector<bool> &flag,vector<int> &num) { if(ans.size()==num.size()) { res.push_back(ans); return; } for(int i=0;i<num.size();i++) { if(i&&num[i]==num[i-1]&&!flag[i-1]) continue; if(!flag[i]) { ans.push_back(num[i]); flag[i]=true; DFS(res,ans,flag,num); flag[i]=false; ans.pop_back(); } } } vector<vector<int> > permuteUnique(vector<int> &num) { sort(num.begin(),num.end());//先排序 vector<vector<int> > res; vector<bool> flag(num.size(),false); vector<int> ans; DFS(res,ans,flag,num); return res; } };