生成格雷码

在一组数的编码中,若任意两个相邻的代码只有一位二进制数不同, 则称这种编码为格雷码(Gray Code),请编写一个函数,使用递归的方法生成N位的格雷码。

给定一个整数n,请返回n位的格雷码,顺序为从0开始。

测试样例:
1
返回:["0","1"]
题目很刁钻,题干很简洁,样例很高冷……
其中有一些微妙的关系  

 

发现了这个规律之后,代码自然就很好写了

class GrayCode:
    def getGray(self, n):
        # write code here
        global maxn
        maxn = n
        return GrayCode.getGrace(self, ['0', '1'], 1)

    def getGrace(self, list_grace, n):
        global maxn
        if n >= maxn:
            return list_grace
        list_befor, list_after = [], []
        for i in xrange(len(list_grace)):
            list_befor.append('0' + list_grace[i])
            list_after.append('1' + list_grace[-(i + 1)])
        return GrayCode.getGrace(self, list_befor + list_after, n + 1)

gary = GrayCode()
gary.getGray(3)

 

 

posted @ 2017-04-08 19:50  kuqs(奇小东)  阅读(339)  评论(0)    收藏  举报