Leetcode: Gray Code

来源:互联网 发布:js 手写板插件 编辑:程序博客网 时间:2024/06/04 20:03

Question

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.

Show Tags
Have you met this question in a real interview? Yes No
Discuss


Solution 1

Get idea from here1, here2

class Solution(object):    def grayCode(self, n):        """        :type n: int        :rtype: List[int]        """        if n==0:            return [0]        res = []        temp = self.grayCode(n-1)        high = 1<<(n-1)        result = temp[:]        for ind in range(len(result)-1,-1,-1):            result.append( high+temp[ind] )        return result

Solution 2

class Solution(object):    def grayCode(self, n):        """        :type n: int        :rtype: List[int]        """        if n==0:            return [0]        res = []        num = 1<<n        for ind in range(num):            res.append((ind>>1)^ind)        return res
0 0
原创粉丝点击