Generate gray code to self-leetcode

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.