Problem description:
Given a collection of integers that might contain duplicates, S, return all possible subsets.
Note:
- Elements in a subset must be 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], [1,2], []]
Analysis: to print out all non-repeated combinations, you can use a flag array to record whether the current element has been used, and then determine whether the element has been reused, the Code is as follows:
Class solution {public: void DFS (vector <int> & S, int beg, int Len, vector <int> & Mid, vector <int> & res, vector <int> & flag) {If (LEN = 0) {res. push_back (MID); return;} If (beg = S. size () return; If (beg = 0 | s [beg]! = S [beg-1] | (s [beg] = s [beg-1] & flag [beg-1] = 1 )) // select the current element {mid. push_back (s [beg]); flag [beg] = 1; DFS (S, beg + 1, len-1, mid, res, flag); flag [beg] = 0; mid. pop_back (); DFS (S, beg + 1, Len, mid, res, flag);} else // The current element {DFS (S, beg + 1, Len, mid, res, flag) ;}}vector <vector <int> subsetswithdup (vector <int> & S) {vector <int> res; int Len = S. size (); If (LEN = 0) return res; vector <int> mid; vector <int> flag (Len, 0); sort (S. begin (), S. end (); For (INT I = 0; I <= Len; ++ I) // a combination of DFS (S, 0, I, mid, res, flag );}};
Leetcode -- subsets II