我想计算不包含两个连续的 OR 3个连续零的位串数
但不是两者
我找到了一个由两个连续的 OR 3个连续零组成的算法,但我找不到它们之间的交集,因为我想排除它..
例如,我的输入是4.我需要找到所有不具有三个连续0或两个连续1的4位长度序列。所以答案是5:0010,0100,0101,1001和1010
任何想法? 感谢..
答案 0 :(得分:1)
您可以使用以下方法:
1...
,则子序列必须以0
开头。00...
,则子序列必须以1
开头。0
或1
开始。其余部分应该从程序中清楚:
public class BitSequences {
public static void main(String[] args) {
for (int i = 0; i <= 64; ++i) {
System.out.println(i + " " + bitSequences(i));
}
}
public static long bitSequences(int length) {
return bitSequences(length, Bit.NONE, Bit.NONE);
}
public static long bitSequences(int length, Bit prePreBit, Bit preBit) {
if (length <= 0) {
return 1;
} else if (preBit == Bit.ONE) {
return bitSequences(length - 1, preBit, Bit.ZERO);
} else if (prePreBit == Bit.ZERO && prePreBit == Bit.ZERO) {
return bitSequences(length - 1, preBit, Bit.ONE);
}
return bitSequences(length - 1, preBit, Bit.ONE)
+ bitSequences(length - 1, preBit, Bit.ZERO);
}
enum Bit {
ZERO,
ONE,
NONE
}
}
使用动态编程可以改进程序,但在您的情况下可能并不重要。 length = 64
的计算在一秒钟内完成。结果:共有109个&#39;&#39; 576(大约2个 28 )位长度为64的位串,其中没有11
或000
。