The gray code is a binary numeral system where the successive values are differ in only one bit. Given a non-negative integer
NRepresenting 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,
[0,2,3,1]
is 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.
Ideas:
Example of grey code sequence, and find the law:
n = 0:0
n = 1:0, 1
n =----0, 1, 3, 2) n = 3:000, 001, 011, 010, 110, 111, 101, 100 (0, 1, 3, 2, 6)In the case of n = 3, the first 4 of grey code includes all gray code for n = 2. The last 4 are the first 4 followed by a 2^2.
Promotion: The first half of the grey code of n = i includes all of the grey code of n = i-1, and the latter half is 2^ (i-1) in the first half of the reverse.
Public classSolution { PublicList<integer> Graycode (intN) {List<Integer> result =NewLinkedlist<>(); if(n<0)returnresult; Result.add (0); intinc = 1; for(inti = 0; I < n; i++) { intSize =result.size (); for(intj=size-1;j>=0;j--) {Result.add (Result.get (j)+Inc); } Inc= Inc<<1; } returnresult;}}
Solution Two: O (n)
Public class Solution { public list<integer> graycode (int n) { ListNew Linkedlist<>(); for (int i = 0; i < 1<<n; i++) result.add (i ^ i>>1); // 1<<n = 2^n return result;}}
Reference
Http://bangbingsyb.blogspot.com/2014/11/leetcode-gray-code.html
*gray Code