LeetCode89 Gray Code

Source: Internet
Author: User

Topic:

The gray code is a binary numeral system where the successive values are differ in only one bit.

Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code . A Gray code sequence must begin with 0 (Medium)

For example, given n = 2, return [0,1,3,2] . Its gray code sequence is:

00-001-111-310-2

Analysis:

Examine the three-bit gray code and the two-bit gray code as follows:

00 01 11 10;

000 001 011 010 110 111 101 100;

You can see the following rules, three-bit gray code is two-bit gray code front plus 0, and reverse two-dimensional gray code front plus 1 get.

So ask N for the gray code, only need to add 0 in front of all n-1 bits, and 1 in the reverse of all the n-1-bit gray code.

Code:

1 classSolution {2  Public:3vector<int> Graycode (intN) {4         if(n = =0) {5             returnvector<int> {0};6         }7vector<int> temp = Graycode (n-1);8vector<int>result;9          for(inti =0; I < temp.size (); ++i) {Ten Result.push_back (Temp[i]); One         } A          for(inti = temp.size ()-1; I >=0; --i) { -Result.push_back (Temp[i] + POW (2N1)); -         } the         returnresult; -     } -};

LeetCode89 Gray Code

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.