Generate Binary Strings of length N using Branch and Bound

The task is to generate a binary string of length N using branch and bound technique Examples:
Input: N = 3 Output: 000 001 010 011 100 101 110 111 Explanation: Numbers with 3 binary digits are 0, 1, 2, 3, 4, 5, 6, 7 Input: N = 2 Output: 00 01 10 11
Approach: Generate Combinations using Branch and Bound :
- It starts with an empty solution vector.
- While Queue is not empty remove partial vector from queue.
- If it is a final vector print the combination else,
- For the next component of partial vector create k child vectors by fixing all possible states for the next component insert vectors into the queue.
Below is the implementation of the above approachÂ
C++
// CPP Program to generate// Binary Strings using Branch and Bound#include <bits/stdc++.h>using namespace std;Â
// Creating a Node classclass Node{public:Â Â Â Â int *soln;Â Â Â Â int level;Â Â Â Â vector<Node *> child;Â Â Â Â Node *parent;Â
    Node(Node *parent, int level, int N)    {        this->parent = parent;        this->level = level;        this->soln = new int[N];    }};Â
// Utility function to generate binary strings of length nvoid generate(Node *n, int &N, queue<Node *> &Q){    // If list is full print combination    if (n->level == N)    {        for (int i = 0; i < N; i++)            cout << n->soln[i];        cout << endl;    }    else    {        int l = n->level;Â
        // iterate while length is not equal to n        for (int i = 0; i <= 1; i++)        {            Node *x = new Node(n, l + 1, N);            for (int k = 0; k < l; k++)                x->soln[k] = n->soln[k];            x->soln[l] = i;            n->child.push_back(x);            Q.push(x);        }    }}Â
// Driver Codeint main(){    // Initiate Generation    // Create a root Node    int N = 3;    Node *root;    root = new Node(NULL, 0, N);Â
    // Queue that maintains the list of live Nodes    queue<Node *> Q;         // Instantiate the Queue    Q.push(root);Â
    while (!Q.empty())    {        Node *E = Q.front();        Q.pop();        generate(E, N, Q);    }Â
    return 0;}Â
// This code is contributed by// sanjeev2552 |
Java
// Java Program to generate// Binary Strings using Branch and BoundÂ
import java.io.*;import java.util.*;Â
// Creating a Node classclass Node {Â
    int soln[];    int level;    ArrayList<Node> child;    Node parent;Â
    Node(Node parent, int level, int N)    {        this.parent = parent;        this.level = level;        this.soln = new int[N];    }}Â
class GFG {Â
    static int N;Â
    // Queue that maintains the list of live Nodes    public static Queue<Node> Q;Â
    // Utility function to generate binary strings of length n    public static void generate(Node n)    {        // If list is full print combination        if (n.level == N) {            for (int i = 0; i <= N - 1; i++) {                System.out.print(n.soln[i]);            }            System.out.println();        }        else {Â
            // Create a new vector for new combination            n.child = new ArrayList<Node>();Â
            int l = n.level;Â
            // iterate while length is not equal to n            for (int i = 0; i <= 1; i++) {                Node x = new Node(n, l + 1, N);                for (int k = 0; k < l; k++) {                    x.soln[k] = n.soln[k];                }                x.soln[l] = i;                n.child.add(x);                Q.add(x);            }        }    }Â
    // Driver code    public static void main(String args[])    {        // Initiate Generation        // Create a root Node        N = 3;        Node root = new Node(null, 0, N);Â
        // Instantiate the Queue        Q = new LinkedList<Node>();        Q.add(root);Â
        while (Q.size() != 0) {            Node E = Q.poll();            generate(E);        }    }} |
Python3
from queue import QueueÂ
# Creating a Node classclass Node:    def __init__(self, parent, level, N):        self.parent = parent        self.level = level        self.soln = [0]*N        self.child = []Â
# Queue that maintains the list of live NodesQ = Queue()Â
# Utility function to generate binary strings of length ndef generate(n):    # If list is full print combination    if n.level == N:        print(''.join(str(x) for x in n.soln))    else:        # Create a new list for new combination        n.child = []Â
        l = n.levelÂ
        # iterate while length is not equal to n        for i in range(2):            x = Node(n, l + 1, N)            x.soln[:l] = n.soln[:l]            x.soln[l] = i            n.child.append(x)            Q.put(x)Â
# Driver codeif __name__ == '__main__':    # Initiate Generation    # Create a root Node    N = 3    root = Node(None, 0, N)Â
    # Instantiate the Queue    Q.put(root)Â
    while not Q.empty():        E = Q.get()        generate(E) |
C#
// C# Program to generate// Binary Strings using Branch and Boundusing System;using System.Collections.Generic;Â
// Creating a Node classpublic class Node {Â Â Â Â public int []soln;Â Â Â Â public int level;Â Â Â Â public List<Node> child;Â Â Â Â public Node parent;Â
    public Node(Node parent,                 int level, int N)    {        this.parent = parent;        this.level = level;        this.soln = new int[N];    }}Â
class GFG{Â Â Â Â static int N;Â
    // Queue that maintains the list of live Nodes    public static Queue<Node> Q;Â
    // Utility function to generate     // binary strings of length n    public static void generate(Node n)    {        // If list is full print combination        if (n.level == N)        {            for (int i = 0; i <= N - 1; i++)            {                Console.Write(n.soln[i]);            }            Console.WriteLine();        }        else        {Â
            // Create a new vector for new combination            n.child = new List<Node>();Â
            int l = n.level;Â
            // iterate while length is not equal to n            for (int i = 0; i <= 1; i++)             {                Node x = new Node(n, l + 1, N);                for (int k = 0; k < l; k++)                 {                    x.soln[k] = n.soln[k];                }                x.soln[l] = i;                n.child.Add(x);                Q.Enqueue(x);            }        }    }Â
    // Driver code    public static void Main(String []args)    {        // Initiate Generation        // Create a root Node        N = 3;        Node root = new Node(null, 0, N);Â
        // Instantiate the Queue        Q = new Queue<Node>();        Q.Enqueue(root);Â
        while (Q.Count != 0)        {            Node E = Q.Dequeue();            generate(E);        }    }}Â
// This code is contributed by Rajput-Ji |
Javascript
// Javascript code for the above approachÂ
// Creating a Node classclass Node {Â Â constructor(parent, level, N) {Â Â Â Â this.parent = parent;Â Â Â Â this.level = level;Â Â Â Â this.soln = new Array(N).fill(0);Â Â Â Â this.child = [];Â Â }}Â
// Queue that maintains the list of live Nodesconst Q = [];Â
// Utility function to generate binary strings of length nfunction generate(n, N) {  // If list is full print combination  if (n.level === N) {    console.log(n.soln.join(""));  } else {    // Create a new list for new combination    n.child = [];Â
    const l = n.level;Â
    // iterate while length is not equal to n    for (let i = 0; i < 2; i++) {      const x = new Node(n, l + 1, N);      x.soln = n.soln.slice();      x.soln[l] = i;      n.child.push(x);      Q.push(x);    }  }}Â
// Driver code(() => {  // Initiate Generation  // Create a root Node  const N = 3;  const root = new Node(null, 0, N);Â
  // Instantiate the Queue  Q.push(root);Â
  while (Q.length > 0) {    const E = Q.shift();    generate(E, N);  }})();Â
Â
// This code is contributed by sdeadityasharma |
Output:
000 001 010 011 100 101 110 111
Time Complexity:Â
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



