A backtracking approach to generate n bit Gray Codes | C # 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 .
using System ; using System . Collections . Generic ; class GFG { static int num ; static void grayCodeUtil ( List < int > res , int n ) { if ( n == 0 ) { res . Add ( num ) ; return ; } grayCodeUtil ( res , n - 1 ) ; num = num ^ ( 1 << ( n - 1 ) ) ; grayCodeUtil ( res , n - 1 ) ; } static List < int > grayCodes ( int n ) { List < int > res = new List < int > ( ) ; num = 0 ; grayCodeUtil ( res , n ) ; return res ; } 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 ] + " STRNEWLINE " ) ; } }