格雷码生成公式:
给定位数 n,i 从 0 取到
n
2
−
1
n^2-1
n2−1
gray(i) = i ^ (i / 2)
如 n = 3:
gray(0) = 0 ^ 0 = 000 ^ 000 = 000
gray(1) = 1 ^ 0 = 001 ^ 000 = 001
gray(2) = 2 ^ 1 = 010 ^ 001 = 011
gray(3) = 3 ^ 1 = 011 ^ 001 = 010
gray(4) = 4 ^ 2 = 100 ^ 010 = 110
gray(5) = 5 ^ 2 = 101 ^ 010 = 111
gray(6) = 6 ^ 3 = 110 ^ 011 = 101
gray(7) = 7 ^ 3 = 111 ^ 011 = 100
python:
class Solution:
def grayCode(self, n: int) -> List[int]:
res = []
for i in range(1<<n):
res.append(i ^ (i>>1))
return res
# 或者下面这样
# return [i^(i>>1) for i in range(1<<n)]
java:
class Solution {
public List<Integer> grayCode(int n) {
List<Integer> res = new ArrayList();
for(int i=0; i<(1<<n); i++)
res.add(i ^ (i>>1));
return res;
}
}