- 题目描述
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 .
题目大意:给定一个数字n,要求在所有长度为n的二进制串中找到不存在连续1的字符串的个数。
思路1:
1、回溯+深搜
长度为n的所有二进制串形成一棵子集树,所以可以用DFS遍历子集树,遍历过程中检查是否有连续的1出现,时间复杂度为O(2^n)。
#include <iostream>
using namespace std;
int ans = 0;
int n;
bool judge(string s)
{
int len = s.length();
for (int i = 0; i < len - 1; i++)
{
if (s[i] == '1' && s[i + 1] == '1')
{
return false;
}
}
return true;
}
void DFS(string s, int depth)
{
if (depth == n)
{
if (judge(s) == true)
{
ans++;
}
return;
}
s += "0";
cout<<s<<endl;
DFS(s, depth + 1);
s[depth] = '1';
cout<<s<<endl;
DFS(s, depth + 1);
}
int main()
{
cin >> n;
string s = "";
DFS(s, 0);
cout << ans << endl;
return 0;
}
思路2:
设a[i]为长度为i的二进制串且不含有连续的1;
则a[1]=2 //0,1
a[2]=3 //00,01,10
若a[i]的第i位为0,那么第i-1位可以是0也可以是1,此种情况的二进制串有a[i-1]个;
若a[i]的第i位为1,那么第i-1位必为0,第i-2位可以是0或1,此种情况的二进制串有a[i-2]个。
所以当n>=3时,a[i]=a[i-1]+a[i-2];
#include<iostream>
#include<cstring>
#include<string>
using namespace std;
const int maxn = 100;
typedef long long ll;
ll dp[maxn];
int main()
{
int n;
cin>>n;
memset(dp,0,sizeof(dp));
dp[1] = 2;
dp[2] = 3;
for(int i=3; i<=n; i++)
{
dp[i] = dp[i-1] +dp[i-2];
}
cout<<dp[n]<<endl;
return 0;
}