This post is completed by 2 users

  • 1
Add to List
Medium

112. Generate All n-Bit Binary Strings

Objec­tive: - Generate All Strings of n bits, consider A[0..n-1] is an array of size n.

Example :

n = 3
Output:
[0, 0, 0]    [1, 0, 0]    [0, 1, 0]    [1, 1, 0]

[0, 0, 1]     [1, 0, 1]     [0, 1, 1]    [1, 1, 1]

Approach:

  1. Recursion is key here.
  2. create an integer array of size n.
  3. Now if we think of every bit, it can take 2 values, 0 and 1.
  4. begin from the last index in the array, set the bits 0 and 1 respectively, and make recursive calls

 

Output:

[0, 0, 0]
[1, 0, 0]
[0, 1, 0]
[1, 1, 0]
[0, 0, 1]
[1, 0, 1]
[0, 1, 1]
[1, 1, 1]