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]
.
The upgraded permutations version is still in full order, but duplicate numbers may appear in the sequence.
Idea: Use the non-recursive method of Lexicographic Order. Starting from an arrangement with the smallest dictionary order, each time the Lexicographic Order is obtained, which is just greater than the previous one, all results are obtained until the largest Lexicographic Order is obtained, take the string "ABC" as an example. "ABC" is the smallest lexicographically ordered sorting. All situations are alphabetically arranged as "ABC", "ACB", "BAC", "BCA ", "CBA", "cab ".
The specific steps are as follows:
1. Sort the strings to obtain the smallest Lexicographic Order (c0c1c2... CN) and CI <= Ci + 1.
2. from the back to the front, find a pair of adjacent ascending elements, Cici + 1 (CI <Ci + 1). If such adjacent ascending pairs cannot be found after the string traversal, it indicates that the largest Lexicographic Order has been reached.
3. From the end position of the string to the position I traversal, find the element CJ greater than the CI, and switch the position of CJ
4. sort all the characters from CI + 1 to CN in reverse order, so that the order is exactly larger than the previous Lexicographic Order (because after conversion, Ci + 1 <Ci + 2 <... <CN, which is the smallest Lexicographic Order ).
5. Repeat 3, 4, and 5 until the maximum Lexicographic Order is reached.
AC code:
class Solution {public: void swap(int &i,int &j) { int temp=i; i=j; j=temp; } vector<vector<int> > permuteUnique(vector<int> &num) { vector<vector<int>> res; int i,j,n=num.size(); sort(num.begin(),num.end()); res.push_back(num); while(true) { for(i=n-2;i>=0;i--) if(num[i]<num[i+1]) break; if(i<=-1) return res; for(j=n-1;j>i;j--) if(num[j]>num[i]) break; swap(num[i],num[j]); for(int k=i+1;k<(i+1+n)/2;k++) swap(num[k],num[n-(k-i)]); res.push_back(num); } }};