2017.10.20
格雷编码,最主要的就是要了解编码产生的过程。
这段是抄别人的,哈哈哈:如n=2时,格雷码为00,01,11,10.如需生成n=3的格雷码只需先将原序列高位加0变成000,001,011,010,再将原序列在高位加1并逆向添加到刚才生成的序列尾部,即000,001,011,010,110,111,101,100。也就是说,n+1位元格雷码是基于n位元格雷码产生的。
public class Solution {
/*
* @param n: a number
* @return: Gray code
*/
public List<Integer> grayCode(int n) {
// write your code here
List<Integer> res = new LinkedList<>();
if(n == 0){
res.add(0);
return res;
}
if(n == 1){
res.add(0);
res.add(1);
return res;
}
List<Integer> list = grayCode(n-1);
for(int i = 0 ;i < list.size(); i++){
res.add(list.get(i));
}
int add = (int)Math.pow(2, n-1);
for(int i = list.size() - 1; i >= 0; i--){
res.add(list.get(i) + add);
}
return res;
}
}