Given A collection of numbers that might contain duplicates, return all possible unique permutations.
For example,
[1,1,2]
The following unique permutations:
[1,1,2]
, [1,2,1]
, and [2,1,1]
.
Show TagsBacktracking This is the input an array, there may be duplicates, the output of all the arrangement. The question called STL is as follows:
1#include <vector>2#include <iterator>3#include <algorithm>4#include <iostream>5 using namespacestd;6 7 classSolution {8 Public:9vector<vector<int> > Permuteunique (vector<int> &num) {Ten intn =num.size (); Onevector<vector<int> >ret; A if(n<1)returnret; - if(n<2) {ret.push_back (num);returnret;} - sort (Num.begin (), Num.end ()); the ret.push_back (num); - while(Next_permutation (Num.begin (), Num.end ())) { - ret.push_back (num); - } + returnret; - } + }; A at intMain () - { -vector<int> num = {1,1,2}; - solution Sol; -vector<vector<int> > RET =sol.permuteunique (num); - for(intI=0; I<ret.size (); i++){ inCopy (Ret[i].begin (), Ret[i].end (),ostream_iterator<int> (cout," ")); -cout<<Endl; to } + return 0; -}
View Code
If you do not call, is to write a next_permutation, in permutations wrote a good many versions, review the implementation of the STL logic it:
- Input array a[], from right-to-left traversal, looking for adjacent two numbers, so that left<mid, not found? Just no, return false.
- Again from the right to the left to traverse, to look for >left, this time you do not need to be connected to the back, because there are 1 of this, so there is a guaranteed value (mid)
- Swap left and right.
- Reverse mid and its right.
- End.
[Leetcode] Permutations II Arrangement