Three algorithms for enumerating all subsets-"Getting Started with algorithms"

Source: Internet
Author: User

Method One: Incremental construction method

Understanding recursion has to understand what a function does.

#include <cstdio>void print_subset (int n,int *a,int cur)  {    printf ("{");    for (int i=0;i<cur;i++) printf ("%d", A[i]);    printf ("}\n");    int mi=cur?a[cur-1]+1:0;  Use dictionary order to avoid duplicate printing for     (int i=mi;i<n;i++)      {        a[cur]= }}int main () {int n; int a[ 10]={}; scanf ("%d",&N); Print_subset (n,a,0);//initially a subset of 0 elements is stored in a, starting to recursively print return 0;}   

Method Two: Bit vector method

Enumeration of each bit or not, the complexity is slightly higher than the method, but better understood, because the output is the same as the whole line of thinking, full n-bit output.

#include <cstdio>int a[10];void print_subset (int n,int *b,int cur)  {    if (cur==n)      {        printf ("{");        for (int i=0;i<n;i++)            if (B[i]) printf ("%d", A[i]); printf ("}\n"); } else }}int main () {int n; int b[10]={}; scanf ("%d",&N); for (int i=0;i<n;i++) a[i]=  I Print_subset (n,b,0); return 0;}             

The disadvantage is that the output is not in dictionary order.

Method 3:2 Binary method

A little thought will find that the two methods are in fact corresponding to the binary system.

#include <cstdio>int a[10];void print_subset (int n,int b)  {    printf ("{");    for (int i=0;i<n;i++)        if (b& (1<<i)) printf ("%d", A[i]);    printf ("}\n");} void p_s (int}int main () {int n; scanf ("%d",&N); for (int i=0;i<n;i++) a[i]=i; p_s (n); ret Urn 0;}           

The advantage of this method is that the code is simple.

Note: The output order of the above three methods is different.

Three algorithms for enumerating all subsets-"Getting Started with algorithms"

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.