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:
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 is able to judge based on one instance of gray code sequence. Sorry about that.
解法1: Recursive O(2^N)
这题一开始没有思路, 对于没思路的可以考虑多写几个最简单的情况的结果来找规律。本题就是一个列子。如果我们把n = 1, n = 2, n = 3的结果写出来就一目了然了。
|
|
|
|
可以发现,对于n的结果,有2^n个数,前2^n-1个数来自于n-1的结果,后一半的数是把n-1的结果倒序后最高位(n)位上加1即可。
有了这个结论,写程序就比较简单了。复杂度应该是O(2^N)
C++
Java