```
def grayCode(self, n):
def flip_bit(num, i):
b = num & (1 << i)
return num & (~(1 << i)) if b else num | (1 << i)
s, visited, res = [0], set(), []
while len(s):
c = s.pop()
if c not in visited:
visited.add(c)
res.append(c)
for i in range(n - 1, -1, -1):
next_ = flip_bit(c, i)
if next_ not in visited:
s.append(next_)
return res
```