简体   繁体   中英

Recursively print Binary subsets of an ArrayList

So I've been wracking my brain over this for a while and, while the code works, it prints it in the absolute wrong order. I feel like I'm missing something so I could use an extra pair of eyes.

void recursiveBitPatterns(ArrayList<String> subsets, int n)
{
    if (n==1)
    {
        subsets.add("0");
        subsets.add("1");
        return;
    }
    recursiveBitPatterns(subsets, n-1);
    int asize = subsets.size();
    for(int i=0; i<asize; i++)
    {
        String nsub = subsets.get(i);
        subsets.set(i, nsub +"0");
        subsets.add(nsub + "1");
    }
}

It seems to be setting the second element of the arraylist to 1 but not overwriting it in the loop.

This prints:

000 100 010 110 001 101 011 111

Any help would be appreciated

As far as I read in your code you are trying to generate all possible subsets from a set of N elements.

let subsets to be the arraylist where the subsets will be stored.

void gen(int N, int subset)  {
    if ( N < 0 ) {
        subsets.add( Integer.toBinaryString(subset) );
        return;
    }

    gen(N - 1, subset);
    gen(N - 1, subset | (1 << N) );
}

call it:

gen( sizeOfSet - 1, 0 );

You code would look like.

void recursiveBitPatterns(ArrayList<String> subsets, int n)
{
    if (n==1)
    {
        subsets.add("0");
        subsets.add("1");
        return;
    }
    recursiveBitPatterns(subsets, n-1);
    int asize = subsets.size();
    for(int i=0; i<asize; i++)
    {
        String nsub = subsets.get(i);
        subsets.set(i, "0" + nsub);
        subsets.add("1" + nsub);
    }
}

This prints:

000 001 010 011 100 101 110 111

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM