简体   繁体   English

递归打印ArrayList的Binary子集

[英]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. 看来是将arraylist的第二个元素设置为1,但不会在循环中覆盖它。

This prints: 打印:

000 100 010 110 001 101 011 111 000100010110001101011111

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. 据我在您的代码中所读,您正在尝试从一组N个元素中生成所有可能的子集。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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