Permutations II
Mar 17 '12
1277 / 3449
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:
vector<vector<int> > permuteUnique(vector<int> &num) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int n = num.size();
sort(num.begin(),num.end());
vector<vector<int> > res;
if(0==n)
return res;
int foot[n];
memset(foot,0,sizeof(int)*n);
int path[n];
int count =0;
sub(res,foot,path,count,n,num);
return res;
}
void sub(vector<vector<int> >&res,int foot[],int path[],int count,int n,vector<int> &num)
{
if(count==n)
{
vector<int> t;
for(int i=0;i<n;i++)
t.push_back(path[i]);
res.push_back(t);
return ;
}
for(int i=0;i<n;)
{
if(!foot[i])
{
foot[i] = 1;
path[count++] = num[i];
sub(res,foot,path,count,n,num);
count--;
foot[i] = 0;
}
while(i<n-1 && num[i]==num[i+1] &&foot[i])
i++;
i++;
}
}
};