89. Gray Code

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

格雷码!!想起了数电中学过的,想起了卡诺图,还会画。。嗯
先放个二元的格雷码感受一下:
00 - 0
01 - 1
11 - 3
10 - 2

可以看到前面一半都是0开头,后面的是1开头,除去开头的部分,剩下的对称。

class Solution(object):
    def grayCode(self, n):
        """
        :type n: int
        :rtype: List[int]
        """
        if n==0:return [0]
        if n==1:return [0,1]
        l1=self.grayCode(n-1)
        def int_to_string(x,n):
            y=bin(x)[2:]
            if len(y)<n:
                y='0'*(n-len(y))+y
            return y
        return l1+[int('1'+int_to_string(i,n-1),2for i in l1[::-1]]

上文中,子函数的作用是把 整数变成长度为n的二进制的字符串,不能直接用bin(),因为对于四元的格雷码,0得有0-000 1-000;而不是0-0 1-0.

讲上诉代码写成迭代的形式的话,如下:

class Solution(object):
    def grayCode(self, n):
        """
        :type n: int
        :rtype: List[int]
        """
        if n==0:return [0]
        if n==1:return [0,1]
        l=[0,1]
        def int_to_string(x,n):
            y=bin(x)[2:]
            if len(y)<n:
                y='0'*(n-len(y))+y
            return y

        for i in xrange(1,n):
            l+=  [int('1' + int_to_string(j, i), 2for j in l[::-1]]

        return l

但是还不够好,是吧,因为只看到了现象没有看到本质。
最开始能看到:
00 - 0
10 - 2
是只有二进制的首位发生了变化,所以写了上诉的两个解法,但是应该深入考虑一下,首位的变化就意味着: 差值是2**(n-1)

这样看前面的string和int就很啰嗦啦~~

于是:
95.56%

class Solution(object):
    def grayCode(self, n):
        if n == 0return [0]
        result = [01]
        for i in xrange(1, n):
            result += [x + 2**i for x in result[::-1]]
        return result

当然也可以用移位来做:
67.18%

class Solution(object):
    def grayCode(self, n):
        if n == 0return [0]
        result = [01]
        for i in xrange(1, n):
            y=1<<i
            result += [x + y for x in result[::-1]]
        return result
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值