Count all possible distinct binary strings of length n with no consecutive 1s
1: Get the max number ending with 0, Get the max number ending with 1
2: For the next max number ending with 0, we just need to append 0 to prev_max_ending_zero + append 0 to prev_max_ending_one
3: For the next max number ending with 1, we can only append 1 to prev_max_ending_zero.
#include <iostream>
#include <vector>
using namespace std;
int totalNumber(int n) {
// ends with 0
int zn = 1;
// ends with 1
int cn = 0;
int total = 0;
for(int i = 1; i <= n; ++i) {
int tmp = zn;
zn = zn + cn;
cn = tmp;
total = zn + cn;
}
return total;
}
int main(void) {
cout << totalNumber(4) << endl;
}
本文介绍了一种算法,用于计算长度为n的不含连续1的不同二进制字符串的数量。通过递推方法,分别计算以0和1结尾的最大数量,最终得出总数量。
2054

被折叠的 条评论
为什么被折叠?



