Problem
The gray code is a binary numeral system where two successive values 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 - 0 01 - 1 11 - 3 10 - 2
Note:
For a given n, a gray code sequence is not uniquely defined.
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 is able to judge based on one instance of gray code sequence. Sorry about that.
Algorithm
Based on solution n, how can we construct solution n+1 ?
n = 2, s2 = [00, 01, 10, 11], Make a copy of s2, and a mirror copy of s2'
t = [00, 01, 10, 11, 11, 10, 01, 00], Then add "0" to left half and "1" to right half
n = 3, s3 = [000, 001, 010, 011, 111, 110, 101, 100]
At middle, the first digit changes, therefore we need a mirror copy of previous solution.
No comments:
Post a Comment