A backtracking approach to generate n bit Gray Codes | JAVA 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 . ; base case when we run out bits to process we simply include it in gray code sequence . ; ignore the bit . ; invert the bit . ; returns the vector containing the gray code sequence of n bits . ; num is passed by reference to keep track of current code . ; Driver function .
import java . util . * ; class GFG { static int num ; static void grayCodeUtil ( Vector < Integer > res , int n ) { if ( n == 0 ) { res . add ( num ) ; return ; } grayCodeUtil ( res , n - 1 ) ; num = num ^ ( 1 << ( n - 1 ) ) ; grayCodeUtil ( res , n - 1 ) ; } static Vector < Integer > grayCodes ( int n ) { Vector < Integer > res = new Vector < Integer > ( ) ; num = 0 ; grayCodeUtil ( res , n ) ; return res ; } 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 ) + "NEW_LINE"); } }