89. Gray Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public List<Integer> grayCode(int n) {
List<Integer> list = new ArrayList<>((int) Math.pow(2, n));
list.add(0);
int powVal = 1;
for (int i = 0; i < n; i++) {
// 注意此处需要镜像,所以倒序
for (int j = list.size() - 1; j >= 0; j--) {
list.add(powVal + list.get(j));
}
powVal <<= 1;
}

return list;
}
}

References

89. Gray Code