5 line efficient python solution

  • 0

    Observing case with n with its sub-problem with n-1, we can find a reverse-and-add relation. That leads to code below.

    class Solution(object):
        def grayCode(self, n):
            :type n: int
            :rtype: List[int]
            results = [0] # base case
            for i in range(n):
            	# get most significant bit value
            	msb = 2**i
            	results += [msb + num for num in results[::-1]]
            return results
            # run in 42 ms

Log in to reply

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