Given a collection of integers that might contain duplicates, S, return all possible subsets.
Note:
- Elements in a subset must is in non-descending order.
- The solution set must not contain duplicate subsets.
For example,
If S = [1,2,2] , a solution is:
[ 2], [1], [1,2,2], [2,2], [up ], []]
Hide TagsArray BacktrackingHas you met this question in a real interview? Yes No
Discuss
Ideas: In the subsets thinking four of the basis of heavy, if there are 3 2, labeled 2a, 2b, 2c, then add 2a, to 2b is the interpretation of the discovery and the front of the same, then only when 2b as the beginning is can join, otherwise you cannot join.
That is, when IDX==DEP, you can join.
Why is it? From DFS (0) Consider, start with 2a and start with 2b is the same, so if 2a starts, 2b does not have to start, then why IDX==DEP when 2b can join?
Because the beginning of the 2a will call the next layer, to 2b, at this time can be added, constitute 2a,2b, that is, two 2 of the case; Since 2b joins, 2c does not have to join because {2a,2b} and {2a,2c} are the same.
classSolution {Vector<vector<int> >M_res; Vector<int>M_array; Public: voidDfsintDEP, vector<int> &S) {m_res.push_back (M_array); for(intIDX = DEP; IDX < s.size (); IDX + +) { //Just add the first elements if there is some duplicates//if idx = = DEP, it should be added if (idx! = DEP && S[idx] = = S[idx-1]) Continue; M_array.push_back (S[idx]); DFS (IDX+1, S); M_array.pop_back (); }} vector<vector<int> > Subsetswithdup (vector<int> &S) {sort (S.begin (), S.end ()); DFS (0, S); returnM_res; }};
classSolution {Vector<vector<int> >M_res; Vector<int>M_array; Vector<BOOL>M_canuse; Public: voidDfsintDEP, vector<int> &S) {m_res.push_back (M_array); for(intIDX = DEP; IDX < s.size (); IDX + +) { if (idx > 0 && m_canuse[idx-1] = = True && S[idx] = = S[idx-1]) Continue; M_array.push_back (S[idx]); M_CANUSE[IDX]=false; DFS (IDX+1, S); M_array.pop_back (); M_CANUSE[IDX]=true; }} vector<vector<int> > Subsetswithdup (vector<int> &S) {sort (S.begin (), S.end ()); M_canuse.clear (); M_canuse.resize (S.size (),true); DFS (0, S); returnM_res; }};
Idea two: Use an array to record whether a number has been used, and if the previous number is the same as this number, the preceding number must be used before it can be used.
[Leetcode] Subsets II