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]
.
第一个版本,加了一个set去除重复
class Solution { public: void sub(vector<vector<int> > & ret,vector<int>& num,int index){ if(index==num.size()){ ret.push_back(num); return ; } int temp; sub(ret,num,index+1); for(int i=index+1;i<num.size();i++){ if(num[i]!=num[index]){ temp=num[i]; num[i]=num[index]; num[index]=temp; sub(ret,num,index+1); temp=num[i]; num[i]=num[index]; num[index]=temp; } } } vector<vector<int> > permuteUnique(vector<int> &num) { // Note: The Solution object is instantiated only once and is reused by each test case. vector<vector<int> >ret; sub(ret,num,0); set<vector<int> > sec(ret.begin(),ret.end()); vector<vector<int> >ret2(sec.begin(),sec.end()); return ret2; } };
第二个版本,改变策略直接填入
class Solution { public: void sub(vector<vector<int> > &ret,vector<int>& num,vector<int>&num2,vector<int>&count,vector<int>& count2,int index){ if(index==num.size()){ ret.push_back(num); return ; } for(int i=0;i<num2.size();i++){ if(count2[i]<count[i]){ num[index]=num2[i]; count2[i]++; sub(ret,num,num2,count,count2,index+1); count2[i]--; } } } vector<vector<int> > permuteUnique(vector<int> &num) { // Note: The Solution object is instantiated only once and is reused by each test case. vector<int>num2; vector<int>count; sort(num.begin(),num.end()); if(num.size()==0)return vector<vector<int> >(); num2.push_back(num[0]); count.push_back(1); for(int i=1;i<num.size();i++){ if(num[i]!=num[i-1]){ num2.push_back(num[i]); count.push_back(1); } else{ count[count.size()-1]++; } } vector<int>count2; count2.resize(count.size(),0); vector<vector<int> >ret; sub(ret,num,num2,count,count2,0); return ret; } };