我想要生成每一个可能的二进制数字序列,其中列表中的每个序列都被限制为1的特定数,并且有填充的零使每个列表都具有相同的长度。
例如,如果序列应该是4个数字,并且有2个数字,那么所有序列都是:
1100  1010  1001  0110 0101 0011
数字前面的零被保留下来。
发布于 2015-07-03 13:05:54
这可以通过递归函数调用来解决:
public class BinarySequences {
    public static void main(String[] args) {
        final int numCount = 4; 
        final int oneCount = 2; 
        checkSubString(numCount, oneCount, "");
        for (String res : results) {
            System.out.println(res);
        }
    }
    private static List<String> results = new ArrayList<>();
    private static void checkSubString(int numCount, int oneCount, String prefix) {
        if ((numCount >= oneCount) && (oneCount >= 0)) {
            if (numCount==1) {
                if (oneCount==1) {
                    results.add(prefix + "1");
                } else {
                    results.add(prefix + "0");
                }
            } else {
                checkSubString(numCount-1, oneCount  , prefix + "0");
                checkSubString(numCount-1, oneCount-1, prefix + "1");
            }
        }
    }
} https://stackoverflow.com/questions/31207301
复制相似问题