In the encoding of a set of numbers, if there is only one binary number in each of the two adjacent codes, the code is called the Gray Code.
The following is an attempt to use a recursive method to generate gray code
vector<int> Graycode (intN) {//n Indicates the number of bits of gray code if(n==0) returnvector<int> (1)//returns a container with only one 0vector<int> Res=graycode (n1);//using recursive methods for(intI=res.size ()-1; I >=0; i--)//adopt a way forward from the backRes.push_back (res[i]+ (i<< (n1))); returnRes; }
Example description: N==0 res={0}
N==1 when res={0,1}//is equivalent to n==0 on the basis of the situation, from the back forward in No. 0 place plus 1, and press into
n==2 res={0,1,11,10}//is equivalent to the n==1 condition, from the back forward in 1th place plus 1, and press into
N==3 when the res={0,1,11,10,110,111,101,100}//equivalent on the basis of n==2, from the back forward in the second place plus 1, and press into
N==4 when the res={0,1,11,10,110,111,101,100,1100,1101,1111,1110,1010,1011,1001,1000}//equivalent on the basis of n==3, from the back forward in the 3rd place plus 1, and press into
Generate gray code to self-leetcode