python - graycode


  • 0
    S
    class Solution(object):
        def do_graycode(self, n, code, answer, seen):
            if len(answer) == (1 << n):
                return True
    
            mask = 1
            for i in range(n):
                new_code = code ^ (mask<<i)
                if new_code not in seen:
                    seen.add(new_code)
                    answer.append(new_code)
                    if not self.do_graycode(n, new_code, answer, seen):
                        seen.remove(new_code)
                        answer.pop()
                    else:
                        return True
            
            return False
                        
                    
                
        def grayCode(self, n):
            """
            :type n: int
            :rtype: List[int]
            """
    
            
            code = 0
            seen = set()
            seen.add(code)
            answer = [code]
            self.do_graycode(n, code, answer, seen)
            
            return answer
    

Log in to reply
 

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