- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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.

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

#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; }

8

- Related Questions & Answers
- C/C++ Program to Count number of binary strings without consecutive 1’s?
- Count number of binary strings without consecutive 1's in C
- Python Program to Count number of binary strings without consecutive 1’
- Count Binary String without Consecutive 1's
- Count number of binary strings of length N having only 0’s and 1’s in C++
- C# program to check if there are K consecutive 1’s in a binary number
- Count the number of 1’s and 0’s in a binary array using STL in C++
- Binary representation of next greater number with same number of 1’s and 0’s in C Program?
- Count 1’s in a sorted binary array in C++
- Count subarrays with equal number of 1’s and 0’s in C++
- Python program to check if there are K consecutive 1’s in a binary number?
- 1’s and 2’s complement of a Binary Number?
- Largest number with binary representation is m 1’s and m-1 0’s in C++
- C# program to find the length of the Longest Consecutive 1’s in Binary Representation of a given integer
- Count subarrays consisting of only 0’s and only 1’s in a binary array in C++

Advertisements