Subsets: generates all subsets of the series & amp; in ascending order.

Source: Internet
Author: User

Subsets: generates all subsets of a series in ascending order.

(1) assuming that the elements of the series are not repeated, for example, [4, 2, 3], we can see that there are a total of 2 ^ 3 = 8 subsets, and an empty set is added;

(2) sort the series to facilitate the generation of sub-sets in ascending order [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 binary number 1 corresponds to the number of corresponding positions in the series. You can obtain the result by traversing it.

(4) Further, what should I do if there are repeated columns? For example, [2, 3, 3] seems complicated because the above method generates many identical subsequences. Yes, the same sub-sequence, but STL provides a good way to solve this problem, that is, the unique algorithm.

(5) unique algorithms should be used properly. Sort before use, and then resize. As follows:

vector
 
   > subsetsWithDup(vector
  
    &S) {       int n= S.size(),idx,tmp;       vector
   
     tuple;       vector
    
     > res;       res.push_back(tuple);       sort(S.begin(),S.end());       if(!n) return res;       for(int i=1; i<(1<
     
      > 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;    }
     
    
   
  
 


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.