The gray code is a binary numeral system where two successive values differ in only one bit.
Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.
For example, given n = 2, return [0,1,3,2]
. Its gray code sequence is:
00 - 0 01 - 1 11 - 3 10 - 2
Note:
For a given n, a gray code sequence is not uniquely defined.
For example, [0,2,3,1]
is also a valid gray code sequence according to the above definition.
For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that.
看看wikipedia的词条就知道这题是怎么回事了。
n=2时候的gray code
00 01 11 10
其反转是
10 11 01 00
而n = 3时候的gray code就是把n=2的gray code前面加上一个0:
000 001 011 010
以及n=2的反转前面加上1:
110 111 101 100
然后把上面的两个List合起来:
000 001 011 010 110 111 101 100
所以这就简单了:integer有32位,所以前面加0可以不用操作,直接把n-1的list拿过来用;前面加1只要反转n-1的list并加上1<<n即可。
public class Solution {
public List<Integer> grayCode(int n) {
List<Integer> res = new ArrayList<Integer>();
res.add(0);
for(int i = 0; i < n; i++){
int header = 1 << i;
int length = res.size();
for(int j = length - 1; j >= 0; j--){
res.add(res.get(j) + header);
}
}
return res;
}
}