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].

C++:
01 void swap(vector<int>&num,int i, int j)
02 {
03     int t=num[i];
04     num[i]=num[j];
05     num[j]=t;
06 }
07 void permuteUniqueHelper(vector<vector<int>>& result, vector<int>& num, int n)
08 {
09     int m=num.size();
10     if(n>=m)
11     {
12         result.push_back(num);
13         return;
14     }
15     set<int> A;
16     for(int i=n;i<m;i++)
17     {
18         if(A.find(num[i])==A.end())
19         {
20             A.insert(num[i]);
21             swap(num,n,i);
22             permuteUniqueHelper(result,num,n+1);
23             swap(num,n,i);
24         }
25     }
26 }
27 class Solution {
28 public:
29     vector<vector<int> > permuteUnique(vector<int> &num) {
30         // Start typing your C/C++ solution below
31         // DO NOT write int main() function
32         vector<vector<int>> result;
33         permuteUniqueHelper(result,num,0);
34         return result;
35     }
36 };
Advertisements
This entry was posted in Array and linked list, Recursive. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s