一、題目
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