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.
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.
Tips:
Note that the binary sequence that satisfies the definition of gray code may be more than one, so the solution indicated in this article is not the only solution.
Considering the gray code adjacent to two binary numbers can only be in one of the differences, so we can use a starting from the lowest, one-bit plus a method to solve the problem, directly see an example, we take n=3 as an example.
We can make the first number 000, then add one at the lowest bit, and all the known gray codes are:
000001
Then we are in the known gray code above, from bottom to top in the sub-low plus one:
000001011010
It is important to note that the order of the addition must be added from the bottom up, because if the new number is generated from the top, then it is equivalent to a change in multiple bits at the same time, and from the bottom up to ensure that only one has changed, and because there is only one difference between the original adjacent gray code, If the same position is added one, the difference between the adjacent two is still only one, so the nature is still established.
At the end of the day we add one to the top, and note or move from bottom to top:
000001011010110111101100
Code:
classSolution { Public: Vector<int> Graycode (intN) {vector<int> Res (1,0); for(inti =0; I < n; ++i) {intSize =res.size (); while(size--) { intCurnum =Res[size]; Curnum+= (1<<i); Res.push_back (Curnum); } } returnRes; }};
"Leetcode" 89. Gray Code