[Leetcode] Grey Code

Source: Internet
Author: User

Title: (backtracking)

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.

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


For a given n, a gray code sequence is not uniquely defined.

For example, was [0,2,3,1] also a valid gray code sequence according to the above definition.

For now, the judge are able to judge based on one instance of gray code sequence. Sorry about that.


Reference http://www.lifeincode.net/programming/leetcode-gray-code-java/

We can see that the last of the digits of 4 codes at the bottom is just the descending sequence of the first 4 codes. The first 4 codes is 0, 1, 3, 2. So, we can easily get the last 4 Codes:2 + 4, 3 + 4, 1 + 4, 0 + 4, which are 6, 7, 5, 4. We can keep doing this until we r each n digits.

To solve this problem, let's take a look at the law of Greycode.

When N=1:



When n=2:





When n = 3:


And then we can find a pattern, and when n increases by 1 each time,

The fact is: 1. Add a 0 to the front of all elements of the n-1.2. N-1 all elements in reverse order followed by 1.

For example, when n=2 n-1 is



All first steps add a 0 to the front of all elements of n-1



The second step is to n-1 all elements in reverse order, followed by 1.



And then because to convert to decimal number, the first step is preceded by 0, that is, add 0, is nothing to add. The second step is preceded by 1, which is exactly the number of all elements added to the n-1.

So the code is as follows:

 Public classSolution { PublicList<integer> Graycode (intN) {List<Integer> ret =NewLinkedlist<>(); Ret.add (0);  for(inti = 0; I < n; i++) {            intSize =ret.size ();  for(intj = size-1; J >= 0; j--) Ret.add (Ret.get (j)+size); }        returnret; }}

[Leetcode] Grey 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.