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
function grayCodeUtil ( res , n , num ) { if ( n == 0 ) { res . push ( num [ 0 ] ) ; return ; } grayCodeUtil ( res , n - 1 , num ) ; num [ 0 ] = num [ 0 ] ^ ( 1 << ( n - 1 ) ) ; grayCodeUtil ( res , n - 1 , num ) ; } function grayCodes ( n ) { let res = [ ] ; let num = [ 0 ] ; grayCodeUtil ( res , n , num ) ; return res ; } let n = 3 ; let code = grayCodes ( n ) ; for ( let i = 0 ; i < code . length ; i ++ ) document . write ( code [ i ] + " " ) ;