一、题目
1. Count number of binary strings without consecutive 1’s
Given a positive integer n(3≤n≤90), count all possible distinct binary strings of length n such that there are no consecutive 1's .
Examples:
Input: 2
Output: 3 // The 3 strings are 00, 01, 10
Input: 3
Output: 5 // The 5 strings are 000, 001, 010, 100, 101
二、题意
给定一个正整数n(3≤n≤90),数出长度为n的所有可能的不同二进制串的个数,使得串中没有连续的1出现。
三、解题思路及算法
1、回溯+深搜
长度为n的所有二进制串形成一棵子集树,所以可以用DFS遍历子集树,遍历过程中检查是否有连续的1出现,时间复杂度为O(2^n)。
// 深搜回溯法
#include <iostream>
using namespace std;
long long total = 0;
bool judge(string s){
int length = s.length();
int num = 0;
for(int i=0; i<length-1; i++){
if(s[i] == '1' && s[i+1] == '1')
return false;
}
return true;
}
void calculate(string s, int index, int n){
if(index == n) {
if(judge(s)){total++;}
return;
}
else{
calculate(s, index+1, n);
s[index] = '1';
calculate(s, index+1, n);
}
}
int main (){
int n;
cin>>n;
string s="";
for(int i=0; i<n; i++){
s+='0';
}
calculate(s, 0, n);
cout<<total<<endl;
return 0;
}
2、动态规划(DP)
思路:设a[i-2],a[i-1], a[i]分别为长度为i-2,i-1,i的不含连续1的二进制字符串的个数
那么从长度为i的来考虑:
1、若最后一个值为0,则这种情况下不含连续1的二进制字符串个数为a[i-1]
2、若最后一个值为1,则这种情况下要符合条件那么倒数第二个的值只能为0
此时符合条件的个数为a[i-2](理由和1相同)
时间复杂度:O(n)。
#include <iostream>
using namespace std;
int main (){
int n;
cin>>n;
long long a[n+1]; // n最大为90,那么总数的量级是2^90数量级,因此需要大数
a[1] = 2; a[2] = 3;
for(int i=3; i<=n; i++){
a[i] = a[i-1] + a[i-2];
}
cout<<a[n]<<endl;
return 0;
}
参考博文:https://blog.csdn.net/climber16/article/details/81604342