Open In App
Related Articles

A backtracking approach to generate n bit Gray Codes

Improve Article
Improve
Save Article
Save
Like Article
Like

Given a number n, the task is to generate n bit Gray codes (generate bit patterns from 0 to 2^n-1 such that successive patterns differ by one bit) 

Examples: 

Input : 2 
Output : 0 1 3 2
Explanation : 
00 - 0
01 - 1
11 - 3
10 - 2

Input : 3 
Output : 0 1 3 2 6 7 5 4
 

We have discussed an approach in Generate n-bit Gray Codes
This article provides a backtracking approach to the same problem. Idea is that for each bit out of n bit we have a choice either we can ignore it or we can invert the bit so this means our gray sequence goes upto 2 ^ n for n bits. So we make two recursive calls for either inverting the bit or leaving the bit as it is. 

C++




// CPP program to find the gray sequence of n bits.
#include <iostream>
#include <vector>
using namespace std;
 
/* we have 2 choices for each of the n bits either we
   can include i.e invert the bit or we can exclude the
   bit i.e we can leave the number as it is. */
void grayCodeUtil(vector<int>& res, int n, int& num)
{
    // base case when we run out bits to process
    // we simply include it in gray code sequence.
    if (n == 0) {
        res.push_back(num);
        return;
    }
 
    // ignore the bit.
    grayCodeUtil(res, n - 1, num);
 
    // invert the bit.
    num = num ^ (1 << (n - 1));
    grayCodeUtil(res, n - 1, num);
}
 
// returns the vector containing the gray
// code sequence of n bits.
vector<int> grayCodes(int n)
{
    vector<int> res;
 
    // num is passed by reference to keep
    // track of current code.
    int num = 0;
    grayCodeUtil(res, n, num);
 
    return res;
}
 
// Driver function.
int main()
{
    int n = 3;
    vector<int> code = grayCodes(n);
    for (int i = 0; i < code.size(); i++)
        cout << code[i] << endl;   
    return 0;
}


Java




// JAVA program to find the gray sequence of n bits.
import java.util.*;
 
class GFG
{
 
static int num;
 
/* we have 2 choices for each of the n bits either we
can include i.e invert the bit or we can exclude the
bit i.e we can leave the number as it is. */
static void grayCodeUtil(Vector<Integer> res, int n)
{
    // base case when we run out bits to process
    // we simply include it in gray code sequence.
    if (n == 0)
    {
        res.add(num);
        return;
    }
 
    // ignore the bit.
    grayCodeUtil(res, n - 1);
 
    // invert the bit.
    num = num ^ (1 << (n - 1));
    grayCodeUtil(res, n - 1);
}
 
// returns the vector containing the gray
// code sequence of n bits.
static Vector<Integer> grayCodes(int n)
{
    Vector<Integer> res = new Vector<Integer>();
 
    // num is passed by reference to keep
    // track of current code.
    num = 0;
    grayCodeUtil(res, n);
 
    return res;
}
 
// Driver function.
public static void main(String[] args)
{
    int n = 3;
    Vector<Integer> code = grayCodes(n);
    for (int i = 0; i < code.size(); i++)
        System.out.print(code.get(i) +"\n");
}
}
 
// This code is contributed by Rajput-Ji


Python3




# Python3 program to find the
# gray sequence of n bits.
 
""" we have 2 choices for each of the n bits
either we can include i.e invert the bit or
we can exclude the bit i.e we can leave
the number as it is. """
def grayCodeUtil(res, n, num):
     
    # base case when we run out bits to process
    # we simply include it in gray code sequence.
    if (n == 0):
        res.append(num[0])
        return
         
    # ignore the bit.
    grayCodeUtil(res, n - 1, num)
     
    # invert the bit.
    num[0] = num[0] ^ (1 << (n - 1))
    grayCodeUtil(res, n - 1, num)
     
# returns the vector containing the gray
# code sequence of n bits.
def grayCodes(n):
    res = []
     
    # num is passed by reference to keep
    # track of current code.
    num = [0]
    grayCodeUtil(res, n, num)
    return res
 
# Driver Code
n = 3
code = grayCodes(n)
for i in range(len(code)):
    print(code[i])
 
# This code is contributed by SHUBHAMSINGH10


C#




// C# program to find the gray sequence of n bits.
using System;
using System.Collections.Generic;
 
class GFG
{
 
static int num;
 
/* we have 2 choices for each of the n bits either we
can include i.e invert the bit or we can exclude the
bit i.e we can leave the number as it is. */
static void grayCodeUtil(List<int> res, int n)
{
    // base case when we run out bits to process
    // we simply include it in gray code sequence.
    if (n == 0)
    {
        res.Add(num);
        return;
    }
 
    // ignore the bit.
    grayCodeUtil(res, n - 1);
 
    // invert the bit.
    num = num ^ (1 << (n - 1));
    grayCodeUtil(res, n - 1);
}
 
// returns the vector containing the gray
// code sequence of n bits.
static List<int> grayCodes(int n)
{
    List<int> res = new List<int>();
 
    // num is passed by reference to keep
    // track of current code.
    num = 0;
    grayCodeUtil(res, n);
 
    return res;
}
 
// Driver function.
public static void Main(String[] args)
{
    int n = 3;
    List<int> code = grayCodes(n);
    for (int i = 0; i < code.Count; i++)
        Console.Write(code[i] +"\n");
}
}
 
// This code is contributed by 29AjayKumar


Javascript




<script>
 
// Javascript program to find the gray sequence of n bits.
 
/* We have 2 choices for each of the n bits either we
can include i.e invert the bit or we can exclude the
bit i.e we can leave the number as it is. */
function grayCodeUtil(res, n, num)
{
     
    // Base case when we run out bits to process
    // we simply include it in gray code sequence.
    if (n == 0)
    {
        res.push(num[0]);
        return;
    }
 
    // Ignore the bit.
    grayCodeUtil(res, n - 1, num);
 
    // Invert the bit.
    num[0] = num[0] ^ (1 << (n - 1));
    grayCodeUtil(res, n - 1, num);
}
 
// Returns the vector containing the gray
// code sequence of n bits.
function grayCodes(n)
{
    let res = [];
 
    // num is passed by reference to keep
    // track of current code.
    let num = [0];
    grayCodeUtil(res, n, num);
 
    return res;
}
 
// Driver code
let n = 3;
let code = grayCodes(n);
for(let i = 0; i < code.length; i++)
    document.write(code[i] + "<br>");
     
// This code is contributed by gfgking
 
</script>


Output: 

0
1
3
2
6
7
5
4

Time Complexity: O(n)
Auxiliary Space: O(n)


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 geeks!

Last Updated : 15 Jun, 2022
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials