Gray Code,求格林码

问题描述:

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

算法分析:首先要明白什么是格林码。给定n,格林码就有2^n个,前面一半是n-1的格林码,后面一半是n-1的格林码的逆序加上1<<(n-1)得到的相邻格林码二进制位只差一位。利用递归即可求解。

1位格雷码有两个码字 
(n+1)位格雷码中的前2^n个码字等于n位格雷码的码字,按顺序书写,加前缀0 
(n+1)位格雷码中的后2^n个码字等于n位格雷码的码字,按逆序书写,加前缀1。

由于是二进制,在最高位加0跟原来的数本质没有改变,所以取得上一位算出的格雷码结果,再加上逆序添1的方法就是当前这位格雷码的结果了。

n = 0时,[0]

n = 1时,[0,1]

n = 2时,[00,01,11,10]

n = 3时,[000,001,011,010,110,111,101,100]

public class GrayCode
{
	public List<Integer> grayCode(int n)
	{
		if(n == 0)
		{
			List<Integer> res = new ArrayList<>();
			res.add(0);
			return res;
		}
		
		List<Integer> res = grayCode(n-1);
		int addNumber = 1 << (n-1);//得到二进制数的十进制
		for(int i = res.size() - 1; i >=0; i --)
		{
			res.add(res.get(i)+addNumber);
		}
		return res;
    }
}
原文地址:https://www.cnblogs.com/masterlibin/p/5810978.html