selected_coding_interview/docs/89. 格雷编码.md
res(即 $G(n)$ )后添加 $R'(n)$ 即可;head = 1 << i 计算出对应位数,以给 $R(n)$ 前添加 $1$ 得到对应 $R'(n)$;res(即 $G(n)$ ):依次求得 $R'(n)$ 各元素添加至 res 尾端,遍历完成后 res(即 $G(n+1)$)。<,,,>
class Solution:
def grayCode(self, n: int) -> List[int]:
res, head = [0], 1
for i in range(n):
for j in range(len(res) - 1, -1, -1):
res.append(head + res[j])
head <<= 1
return res
class Solution {
public List<Integer> grayCode(int n) {
List<Integer> res = new ArrayList<Integer>() {{ add(0); }};
int head = 1;
for (int i = 0; i < n; i++) {
for (int j = res.size() - 1; j >= 0; j--)
res.add(head + res.get(j));
head <<= 1;
}
return res;
}
}