If order doesn't matter, one-line Python solution


  • -6
    P

    I am not sure why order matters here. The intuition is to gather all the elements that have difference in one bit, thus 0 to 2^n

     class Solution(object):
         def grayCode(self, n):
            return range(2**n)
    
    
    
    grayCode(0) = [0]
    
    0    0
    
    grayCode(1) = [0, 1]
    
    0    0
    
    1    1
    
    grayCode(2) = [0, 1, 2, 3]
    
    0     00
    
    1     01
    
    2     10
    
    3     11
    
    grayCode(4) = [0, 1, 2, 3, 4, 5, 6, 7]
    
    
    0     000
    
    1     001
    
    2     010
    
    3     110
    
    4     100
    
    5     101
    
    6     110
    
    7     101
    
    
    ....

  • 0
    S

    I think you have misunderstanding for Grey Code. Please refer wiki link to see whether this is helpful. https://en.wikipedia.org/wiki/Gray_code.

    In a upshot, any adjacent number should differ in ONLY ONE bit.


  • 0
    G

    1 and 2 differ in two digits so they can't be adjacent to each other. so is 5 and 6
    1 is 01
    2 is 10


Log in to reply
 

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