Subsets given a sequence & generate all subsets of the series & Ascending

Source: Internet
Author: User

(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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.