"Leetcode" Gray Code

Source: Internet
Author: User

Gray Code

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:

00-001-111-310-2

Note:
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.

Solution:

If you do not think deeply, you may search directly, that is, every time you try to change the last one of the "01 string" has been constructed, if it has not been added to the ANS set and add it as the last structure of the "01 string" Update. It is important to note that the lookup criteria need to be updated as long as a new legal string is found (i.e., to continue searching based on the string just found).

The code is as follows:

1 classSolution:2     #@param {integer} n3     #@return {integer[]}4     defGraycode (self, n):5SELF.N = 1 <<N6Self.hasget = [False] *SELF.N7Self.hasget[0] =True8Self.len = 19SELF.STR = [0] *NTenSelf.ans =[0] One self.search (n) A         returnSelf.ans -  -     defSearch (self, n): the          whileSelf.len <SELF.N: -              forIinchrange (n): - Self.reverse (i) -num =self.getnum (n) +                 ifSelf.hasget[num]: - Self.reverse (i) +                 Else: A self.ans.append (num) atSelf.hasget[num] =True -Self.len + = 1 -                      Break -  -     defreverse (self, i): -         ifSelf.str[i] = = 1: inSelf.str[i] =0 -         Else: toSelf.str[i] = 1 +  -     defGetnum (self, n): theans, prod = 0, 1 *          forIinchrange (n): $             ifSelf.str[i] = = 1:Panax NotoginsengAns + =prod -Prod *= 2 the         returnAns

Can be passed, but not efficient enough.

The crux of the matter is that we are only blindly searching and testing for the current last "01 strings" Change one after another, the specific performance in the code, from the lowest bit to the highest order to be tempted (for I in range (n)).

But this sort of order in this search is completely random disorderly thinking, but also here led to code efficiency is not high enough.

Do we have a strategy that makes it possible for me to change a certain bit of a "01 string" That already exists in ans every time, so that it must be the legal string we're looking for?

Also said, we can not test, directly to find the string we need, and then change our designated one, is we immediately looking for the new "01 string."

This strategy is not hard to find thanks to the elegance and simplicity of binary.

Considering a state like this, we have found the binary number of all n bits and bits less than n, now how do we legitimately extend the n+1 bit?

This time, the whole ans set already has the number of 2^n, at this time I no matter again change 1-n any one is no longer legitimate we are looking for a new string (because all n-bit binary has been found, and then change the 1-n bit of any one no longer produce a "new solution").

Therefore, the number of 2^n+1 must be on the basis of the number of 2^n, will be n+1 position 1 after the new n+1 bit binary string, that is, the need to find the "new solution."

So how do we introduce more from this "new solution"?

Still focus on the "old solution" we've already found.

The number of 2^n and the number of 2^n+1 is n+1, and the number of 2^n and 2^n-1 must be in the 1..N bit and only one is different. It can be learned that the number of 2^n+1 and the number of 2^n-1 two is different, that is, the n+1 bit becomes 1, and then the 1..N bit and only a certain one is not the same. How are we going to get a new solution now?

Very simple, the first 2^n-1 number of n+1 bit into 1 is that we have found the number of 2^n+1 after the "new solution", that is, the number of 2^n+2!

Similarly, with the "number of neighbors and only a different" rule, we can "forward" all the way to scan the number of 2^n we have received, each time just put their n+1 position 1, and then confidently added to the ANS set of the last face, is what we need to get the "new solution." So we use the already obtained "solid binary flip one of the chain" again back to the construction, play a back and forth, the new same number of solutions come out!

(For a n+1 bit binary number, a number of n+1 0 must be able to find another number n+1 bit 1, making their 1..N bits exactly the same.) The total number of n+1 0 is exactly the same as the total number of n+1 1, so the size of the ANS set is increased by one time for each current highest loop.

The code is as follows:

1 classSolution:2     #@param {integer} n3     #@return {integer[]}4     defGraycode (self, n):5Ans =[0]6          forIinchrange (n):7p = 1 <<I8s =len (ans)9              whiles >0:TenS-= 1 Onev = P |Ans[s] A Ans.append (v) -         returnAns

"Leetcode" 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.