使用ArrayList以Java的形式递归生成二进制字符串

时间:2013-10-28 00:52:51

标签: java algorithm recursion arraylist binary

我想根据用户输入找到任意大小的2 ^ n个排列。我不知道该怎么做。我知道我必须使用递归。与我见过的大多数示例不同,函数的参数只是数字输入,没有可用于进行所有排列的字符串。所有排列都将存储在arrayList中并输出给用户。 即(输入3) 输出: 000 001 010 011 100 101 110 111 这是我到目前为止的代码:

public static void printBin(int bits) {
    ArrayList<String> binaryArray = new ArrayList<String>();

    if(bits == 0) {
        System.out.println(binaryArray);
    }
    else {
        for (String string2 : binaryArray) {
            String comp = "";
            if (comp.length() <= string2.length()) {
                comp = string2;
                string = comp;
            }
            string.concat("0");
            binaryArray.add(string);
            printBin(bits - 1);
            string.concat("1");
            binaryArray.add(string);
            printBin(bits-1);
        }


    }
}

提前致谢。

2 个答案:

答案 0 :(得分:1)

这就是我认为你能做的最好的事情。

import java.util.ArrayList;

public class BinaryList {

    public static void main(String[] args) {
        try {
            if (args.length != 1 || Integer.parseInt(args[0]) < 1)) {
                System.err.println("Invalid integer argument");
                return;
            }

            binaryRecursive(Integer.parseInt(args[0]), new ArrayList<String>(0));

        } catch (NumberFormatException e) {
            System.err.println("Argument not an integer");
        }
    }

    public static void binaryRecursive(int bits, ArrayList<String> list) {

        if (list.size() == (int)Math.pow(2, bits)) {
            for (String n : list) {
                System.out.println(n);
            }

        } else {
            StringBuilder n = new StringBuilder(bits);

            for (int i = bits - 1; i >= 0; i--) {
                n.append((list.size() >> i) & 1);
            }

            list.add(n.toString());

            binaryRecursive(bits, list);
        }
    }
}

如果没有将last作为参数传递,返回值或将列表保留为字段,则无法保留它们的列表。

遵循逻辑通过比特== 2你得到的是:

* 1st method call

list.size() == 0

for 1 to 0 {
    (00 >> 1 = 00) & 01 == 0
    (00 >> 0 = 00) & 01 == 0
}

list.add("00")

* 2nd method call

list.size() == 1

for 1 to 0 {
    (01 >> 1 = 00) & 01 == 0
    (01 >> 0 = 01) & 01 == 1
}

list.add("01")

* 3rd method call

list.size() == 2

for 1 to 0 {
    (10 >> 1 = 01) & 01 == 1
    (10 >> 0 = 10) & 01 == 0
}

list.add("10")

* 4th method call

list.size() == 3

for 1 to 0 {
    (11 >> 1 = 01) & 01 == 1
    (11 >> 0 = 11) & 01 == 1
}

list.add("11")

* 5th method call

list.size() == 4 == 2 ^ 2

print the list

答案 1 :(得分:0)

你从n开始..我想要n = 3位。你的main函数调用一个函数“genBin”,传递一个参数(“0”,n-1)和另一个参数(“1”,n-1)。 genBin返回一个List。 main函数将两个列表合并为一个ArrayList。

genBin(String in,int bitsLeft),如果bitsLeft&gt; 0,用(“0”+ in,bitsLeft-1)和(“1”+ in,bitsLeft-1)调用自身,并将两个返回值合并为ArrayList。如果bitsLeft == 0,则返回单个元素ArrayList。

你的主要功能,在我之前提到的合并之后,最终得到了所有排列的合并列表。