迭代所有可能的组合

时间:2015-04-05 17:49:26

标签: c++ combinatorics

我的目标是迭代给定数量的1和0的所有组合。比方说,如果给出数字5,那么列出

的方法就足够了

1110100100, 1011000101等 (5 1&#5和5 0的每个不同组合

我试图避免迭代所有可能的排列并检查5 1是否存在,因为2 ^ n远大于(n选择n / 2)。感谢。

更新

可以使用以下方法有效地计算答案(递归10深)

// call combo() to have calculate(b) called with every valid bitset combo exactly once
combo(int index = 0, int numones = 0) {
    static bitset<10> b;
    if( index == 10 ) {
        calculate(b); // can't have too many zeroes or ones, it so must be 5 zero and 5 one
    } else {
        if( 10 - numones < 5 ) { // ignore paths with too many zeroes
            b[index] = 0;
            combo(b, index+1, numones);
        }
        if( numones < 5 ) { // ignore paths with too many ones
            b[index] = 1;
            combo(b, index+1, numones++);
        }
    }
}

(以上代码未经过测试)

2 个答案:

答案 0 :(得分:0)

您可以转换问题。如果您修复1 s(反之亦然),那么只需将0放在哪里即可。对于5 1 s,有5 + 1个二进制位,并且您希望将5个元素(0 s)放入二进制位。

这可以通过每个bin的递归和每个bin的循环来解决(在bin中放置0 ...扩孔元素 - 除了最后一个bin,你必须放置所有的remaning元素)。

答案 1 :(得分:0)

考虑它的另一种方式是作为string permutation question的变体 - 只需构建一个长度为2n的向量(例如111000),然后使用相同的算法进行字符串置换来构建结果。

请注意,朴素算法会打印重复的结果。但是,通过在递归函数中保留bool数组来保持为特定位设置的值,可以很容易地调整算法以忽略这样的重复。