(1) First assume that the elements of the series are not duplicated, for example [4, 2, 3], there is a total of 2^3=8 subsets, in addition an empty set;
(2) Sorting sequence, can be easily generated subset ascending [2, 3, 4];
(3) Each subset corresponds to a binary value, 0-Empty set 1-> (2) 2-> (3) 3-> (2,3) ... 7-> (2,3,4), the position of the binary number 1 corresponds to the number of corresponding positions in the sequence. The result can be obtained by traversing over again.
(4) Further, what if the sequence is repeated? For example [2, 3, 3], it seems that all of a sudden complicated, because the above method produces a lot of the same sub-sequences. Yes, the same subsequence, but STL provides a good way to solve this problem, is the unique algorithm.
(5) Unique algorithm to use. Use the first sort before using to resize. As follows:
vector<vector<int> > Subsetswithdup (vector<int> &s) { int n= s.size (), idx,tmp; Vector<int> tuple; vector<vector<int>> Res; Res.push_back (tuple); Sort (S.begin (), S.end ()); if (!n) return res; for (int i=1; i< (1<<n); ++i) { idx=-1; Tuple.clear (); tmp=i; while (TMP) { idx++; if (TMP & 1) tuple.push_back (S[idx]); tmp= (TMP >> 1); } Res.push_back (tuple); } Sort (Res.begin (), Res.end ()); Auto It=unique (Res.begin (), Res.end ()); Res.resize (Distance (Res.begin (), it)); return res; }
Subsets given a sequence & generate all subsets of the series & Ascending