标签:
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]
.
1 class Solution { 2 public: 3 vector<vector<int> > permuteUnique(vector<int> &num) { 4 5 sort(num.begin(),num.end()); 6 vector<vector<int> > result; 7 vector<int> tmp; 8 vector<bool> visited(num.size()); 9 dfs(0,num,result,visited,tmp); 10 return result; 11 12 } 13 14 15 void dfs(int level,vector<int> &num,vector<vector<int> > &result,vector<bool> &visited,vector<int> &tmp) 16 { 17 if(level==num.size()) 18 { 19 result.push_back(tmp); 20 return; 21 } 22 23 for(int i=0;i<num.size();i++) 24 { 25 if(!visited[i]) 26 { 27 if(i>=1&&((num[i]==num[i-1]&&visited[i-1])||(num[i]!=num[i-1]))||i==0) 28 { 29 visited[i]=true; 30 tmp.push_back(num[i]); 31 dfs(level+1,num,result,visited,tmp); 32 tmp.pop_back(); 33 visited[i]=false; 34 } 35 } 36 } 37 } 38 39 };
标签:
原文地址:http://www.cnblogs.com/reachteam/p/4215212.html