What if there are repeated elements?
If you don't need to shoot your head, you will think of a method that is also a common processing method for all elements with duplicates. Maintain a set. If this element is not added, it will be added and ignored. However, this general method times out!
What should I do? Let's take a look at the reason. If the number we want to arrange is 1111112, when there is no 1 in the current arrangement, which one is used to generate it is the same. Only when the current one has been used, it must be the turn of this one to play, it will be valuable. More specifically, if we want to put two 1 s in the generated arrangement, then the two 1 s are the original two which do not matter at all. The final result is certainly the same, however, when we want to place three values in the arrangement, the option 1 must be new and meaningful.
In the language of the algorithm, all candidate numbers are sorted in order, and the same numbers are placed together. For the same numbers, the first one is sorted first, if you want to add the same numbers behind it to the arrangement, you must ensure that the same numbers before it are already in the arrangement, so as to avoid generating repeated arrays.
class Solution {public: set<vector<int> > vis; void getPerm(vector<int> &num, vector<int> &tpres, vector<vector<int> > &res, int len, int n, bool *visited){ if(len == n){ if(vis.find(tpres) == vis.end()){ vis.insert(tpres); res.push_back(tpres); } return; } for(int i=0;i<n;i++){ if(!visited[i]){ if(i!=0&&num[i] == num[i-1]&&!visited[i-1]) continue; visited[i] = 1; tpres.push_back(num[i]); getPerm(num, tpres, res, len+1, n, visited); visited[i] = 0; tpres.pop_back(); } } } vector<vector<int> > permuteUnique(vector<int> &num) { vector<vector<int> > res; vector<int> tpres; int msize = num.size(); if(msize<=0) return res; bool visited[msize]; memset(visited, 0, sizeof(visited)); sort(num.begin(), num.end()); getPerm(num, tpres, res, 0, msize, visited); return res; }};