Very easy solution with thinking


  • 0
    R

    (n+1) bit gray code can be derived from n bit gray code

    For example, 2-bit gray codes are:
    00
    01
    11
    10

    we can put 0 and 1 on the leftmost bit of gray codes above, and make sure every time only 1 bit is changed:

    000
    100

    101
    001

    011
    111

    110
    010

    Here is my code, but gray codes created in this way cannot be correctly judged...

    class Solution(object):
        def grayCode(self, n):
            if n==0:
                return [0]
            if n==1:
                return [0,1]
            i=2
            frontier=[0,1,3,2]
            while i!=n:
                k=0
                next=[]
                while k<len(frontier):
                    next.append(frontier[k])
                    next.append(frontier[k]|1<<i)
                    k+=1
                    next.append(frontier[k]|1<<i)
                    next.append(frontier[k])
                    k+=1
                frontier=next
                i+=1
            return frontier
    
            
    

Log in to reply
 

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