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 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.
C Solution 1:
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int* grayCode(int n, int* returnSize) {
*returnSize = 1 << n;
int *res = malloc(*returnSize * sizeof(int));
res[0] = 0;
int len = 1;
while (n--) {
int i, _len = len;
for (i = _len - 1; i > -1; i--) {
res[len++] = _len | res[i];
}
}
return res;
}
C Solution 2:
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int* grayCode(int n, int* returnSize) {
*returnSize = 1 << n;
int *res = malloc(*returnSize * sizeof(int));
int i;
for (i = 0; i < *returnSize; i++) {
res[i] = i ^ (i >> 1);
}
return res;
}
Python Solution:
class Solution(object):
def grayCode(self, n):
"""
:type n: int
:rtype: List[int]
"""
if n < 1: return [0]
res = [0] * (1 << n)
res[1] = 1
ind = cur_size = 2
for k in range(1, n):
mask = 1 << k
for i in reversed(xrange(cur_size)):
res[ind] = res[i] | mask
ind += 1
cur_size = ind
return res
Summary:
- Solution 2 is something ... special.
LeetCode: 89. Gray Code





近期评论