Word Search @ LeetCode (Python)
Construct Binary Tree from Preorder and Inorder Traversal @ LeetCode (Python)

Gray Code @ LeetCode (Python)

kitt posted @ 2014年4月13日 22:14 in LeetCode , 3034 阅读
class Solution:
    # @return a list of integers
    def grayCode(self, n):
        if n == 0: return [0]
        L = [0, 1]
        for i in xrange(2, n + 1):
            t = 1 << (i - 1)
            L = L + [ j + t for j in L[::-1] ]
        return L

另一种解法:

class Solution:
    # @param {integer} n
    # @return {integer[]}
    def grayCode(self, n):
        # from wikipedia, https://en.wikipedia.org/wiki/Gray_code
        # binaryToGray: return (num >> 1) ^ num, i.e. (num / 2) XOR num
        # grayToBinary:
        # unsigned int mask;
        # for (mask = num >> 1; mask != 0; mask = mask >> 1)
        #     num = num ^ mask;
        # return num;
        return [(i >> 1) ^ i for i in xrange(2 ** n)] 

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter