Gray Code
lc 89
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.
given n = 2, return [0,1,3,2]. Its gray code sequence is:
00 - 0
01 - 1
11 - 3
10 - 2
当n=3时,正确的GrayCode应该是
000
001
011
010
110
111 //如果按照题意的话,只是要求有一位不同,这里也可以是100
101
100
GrayCode的规律就出来了,n=k时的Gray Code,相当于n=k-1时的Gray Code的逆序 加上 1<<k。
public List<Integer> grayCode(int n) {
List<Integer> res = new ArrayList<Integer>();
if(n == 0){
res.add(0);
return res;
}
if( n == 1){
res.add(0);
res.add(1);
return res;
}
List<Integer> last = grayCode(n - 1);
for(int i = 0; i < last.size(); i++){
res.add(last.get(i));
}
for(int i = last.size() - 1; i >= 0; i--){
int cur = (1 << (n- 1)) + last.get(i);
res.add(cur);
}
return res;
}