A backtracking approach to generate n bit Gray Codes | 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 Code
def grayCodeUtil ( res , n , num ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT res . append ( num [ 0 ] ) NEW_LINE return NEW_LINE DEDENT grayCodeUtil ( res , n - 1 , num ) NEW_LINE num [ 0 ] = num [ 0 ] ^ ( 1 << ( n - 1 ) ) NEW_LINE grayCodeUtil ( res , n - 1 , num ) NEW_LINE DEDENT def grayCodes ( n ) : NEW_LINE INDENT res = [ ] NEW_LINE num = [ 0 ] NEW_LINE grayCodeUtil ( res , n , num ) NEW_LINE return res NEW_LINE DEDENT n = 3 NEW_LINE code = grayCodes ( n ) NEW_LINE for i in range ( len ( code ) ) : NEW_LINE INDENT print ( code [ i ] ) NEW_LINE DEDENT