二进制数是仅包含两个的数字,即具有一个或两个。每个二进制数都是一个二进制位流,我们将其视为二进制字符串。对于此字符串,我们需要找到不包含连续N位的二进制字符串的数目。
例如,对于N-5,满足给定约束的二进制字符串为00000 00001 00010 00100 00101 01000 01001 01010 10000 10001 10010 10100 10101
一种方法是生成所有N位数字的字符串,并仅打印满足给定约束的那些字符串。但是,这种方法在工作时效率不高。
另一种方法是使用递归。在递归的每个点上,我们将0和1附加到部分形成的数字上,并递减一位。这里的窍门是,我们仅在部分形成的数字的最后一位为0时才追加1并重复出现。这样,我们在输出字符串中将永远不会有任何连续的1。
Input: n = 5 Output: Number of 5-digit binary strings without any consecutive 1's are 13
#include <iostream>
#include <string>
using namespace std;
int countStrings(int n, int last_digit) {
if (n == 0)
return 0;
if (n == 1) {
if (last_digit)
return 1;
else
return 2;
}
if (last_digit == 0)
return countStrings(n - 1, 0) + countStrings(n - 1, 1);
else
return countStrings(n - 1, 0);
}
int main() {
int n = 5;
cout << "Number of " << n << "-digit binary strings without any "
"consecutive 1's are " << countStrings(n, 0);
return 0;
}