用C / C ++程序计算不带连续1的二进制字符串的数目?
二进制数是仅包含两个的数字,即具有一个或两个。每个二进制数都是一个二进制位流,我们将其视为二进制字符串。对于此字符串,我们需要找到不包含连续N位的二进制字符串的数目。
例如,对于N-5,满足给定约束的二进制字符串为00000000010001000100001010100001001010101000010001100101010010101
一种方法是生成所有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;
}热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短