题目来源:
https://leetcode.com/problems/gray-code/
题意分析:
给定一个n,返回他的一个格雷序列。比如n=2,[0,1,3,2]是他的一个格雷序列。格雷序列就是,长度为n的二进制,起始序列是全是0,而下一个序列和上一个序列只相差一个bit。也就是00,01,11,10,两两之间的字符相差只有一个字节。
题目思路:
格雷序列是有很多个结果的。我觉得这个题目的难度不在于找到一个格雷序列,而是要找到出题者的序列,因为题目只有一个特定的序列。最简单的格雷序列就是刚开始0,然后将小于2^n所有的奇数从大到小列出,然后将小于2^n所有的偶数由大到小列出。而出题者要求的格雷码是将前一个数右移一位,然后和原来的进行^操作。
代码(Python):

import math class Solution(object): def grayCode(self, n): """ :type n: int :rtype: List[int] """ if n == 0: return [0] m = pow(2,n) - 1 ans = [0,1] i = 3 while i <= m: ans.append(i) i += 2 i -= 3 while i > 0: ans.append(i) i -= 2 return ans

import math class Solution(object): def grayCode(self, n): """ :type n: int :rtype: List[int] """ ans = [] size = pow(2,n) for i in range(size): ans.append((i >> 1)^i) return ans