题目1
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 .
Input: 2
Output: 3 // The 3 strings are 00, 01, 10
Input: 3
Output: 5 // The 5 strings are 000, 001, 010, 100, 101
先上dfs,时间复杂度太高
#include<iostream>
using namespace std;
int n;
const int MAXN=100;
long long ans;
void dfs(int now,int con)
{
if(con>1) //减枝
return ;
if(now==n )
{
ans++;
return ;
}
dfs(now+1,0);
dfs(now+1,con+1);
}
int main()
{
cin>>n;
dfs(0,0); //从下标0开始,末尾连续1的个数
cout<<ans;
return 0;
}
比较容易想的dp
#include<iostream>
using namespace std;
int n;
const int MAXN=105;
long long dp[105][2];
int main()
{
cin>>n;
dp[1][0]=1;
dp[1][1]=1;
for(int i=2;i<=n;i++)
{
dp[i][1]=dp[i-1][0];
dp[i][0]=dp[i-1][0]+dp[i-1][1];
}
cout<<dp[n][1]+dp[n][0];
return 0;
}
第二种dp dp[i]=dp[i-1]+dp[i-2] //dp[i]表示前i位没有连续的1
//当第i位为1,dp[i]=dp[i-2] 当第i位为0,dp[i]=dp[i-1]