4 line Python solution extremely simple


  • 1
    L
    class Solution(object):
        def grayCode(self, n):
            """
            :type n: int
            :rtype: List[int]
            """
            result = [0]
            for i in xrange(n):
                result.extend([result[j] | (1 << i) for j in reversed(xrange(len(result)))])
            return result
    

    Similar to the solution in https://discuss.leetcode.com/topic/58660/dp-python-solution, but go even further in reducing the space complexity.

    Every time one more digit is considered, I duplicate the existing result in reverse order, and at the same time append a '1' to the leading bit of the numbers in the duplicated half.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.