您的问题归结为找到 4 选择 2 的所有组合。您获取零索引的想法是一个很好的起点。
对于给定的示例1100010,我们有以下内容:
1 1 0 0 0 1 0
| | | | | | |
V V V V V V V
0 1 2 3 4 5 6 // indices here assuming base 0
因此我们的零索引向量是{2, 3, 4, 6}。
现在,我们可以生成我们的零索引向量选择 2 的所有组合(在 SO 或网络上有几种很好的算法),并进行适当的替换以生成我们的输出。
伪代码:
inputVec = {1,1,0,0,0,1,0}
zeroIndex = {}
for i in 0 to (length(inputVec) - 1)
if (inputVec[i] == 0)
zeroIndex.push_back(i) // zeroIndex = {2, 3, 4, 6} for the given example
// initialize output vector to the input vector
newOutput = inputVec
myCombos = generateCombos(zeroIndex, 2) // matrix of combinations with 2 columns
for i in 0 to (length(myCombos) - 1) {
newOutput[myCombos[i, 0]] = 1
newOutput[myCombos[i, 1]] = 1
print(newOutput)
// reset output vector
newOutput = inputVec
}
在上述算法中,generateCombos 将输出以下内容:
[,0] [,1]
[0,] 2 3
[1,] 2 4
[2,] 2 6
[3,] 3 4
[4,] 3 6
[5,] 4 6
概述的算法扩展到输入向量具有任意长度并且具有任意数量的 0 和 1 的一般情况。