Here we will see one interesting problem. Suppose one value of n is given. We have to find all strings of length n, such that there are no consecutive 1s. If n = 2, then the numbers are {00, 01, 10}, So output is 3.
We can solve it using dynamic programming. Suppose we have a tables ‘a’ and ‘b’. Where arr[i] is storing the number of binary strings of length i, where no consecutive 1s are present, and ending with 0. Similarly, b is holding the same but numbers ending with 1. We can append 0 or 1 where last one is 0, but add only 0 if the last one is 1.
Let us see the algorithm to get this idea.
Algorithm
noConsecutiveOnes(n) −
Begin define array a and b of size n a[0] := 1 b[0] := 1 for i in range 1 to n, do a[i] := a[i-1] + b[i - 1] b[i] := a[i - 1] done return a[n-1] + b[n-1] End
Example
#include <iostream>
using namespace std;
int noConsecutiveOnes(int n) {
int a[n], b[n];
a[0] = 1;
b[0] = 1;
for (int i = 1; i < n; i++) {
a[i] = a[i-1] + b[i-1];
b[i] = a[i-1];
}
return a[n-1] + b[n-1];
}
int main() {
cout << noConsecutiveOnes(4) << endl;
}Output
8