[LeetCode] 89. Gray Code Java

题目:

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.

题意及分析:给出一个整数,要求求出格雷码。格雷码(Gray Code)是一个数列集合,每个数使用二进位来表示,假设使用n位元来表示每个数字,任两个数之间只有一个位元值不同。例如以下为3位元的格雷码: 000 001 011 010 110 111 101 100 。如果要产生n位元的格雷码,那么格雷码的个数为2^n. 观察可以发现格雷码除了第一位外 格雷码是上下对称的,比如第一个格雷码与最后一个格雷码对称(除了第一位),第二个格雷码与倒数第二个对称,以此类推。

所以,在实现的时候,我们完全可以利用递归,在每一层前面加上0或者1,然后就可以列出所有的格雷码。
比如:
第一步:产生 0, 1 两个字符串。
第二步:在第一步的基础上,每一个字符串都加上0和1,但是每次只能加一个,所以得做两次。这样就变成了 00,01,11,10 (注意对称)。
第三步:在第二步的基础上,再给每个字符串都加上0和1,同样,每次只能加一个,这样就变成了 000,001,011,010,110,111,101,100。
好了,这样就把3位元格雷码生成好了。
如果要生成4位元格雷码,我们只需要在3位元格雷码上再加一层0,1就可以了: 0000,0001,0011,0010,0110,0111,0101,0100,1100,1101,1110,1010,0111,1001,1000.
 
也就是说, n位元格雷码是基于n-1位元格雷码产生的。
 
因为这里最后需要的是整数,对于每一次在前面加0,值不变;加一则需要加上1*2^(当前数的位数-1),代码如下
代码:
public class Solution {
    public List<Integer> grayCode(int n) {
	    List<Integer> result = new LinkedList<>();
	    if(n==0){
	    	result.add(0);
	    	return result;
	    }
	    if(n==1){
	    	result.add(0);
	    	result.add(1);
	    	return result;
	    }
	    int[] res=produce(n);
	    for(int i=0;i<res.length;i++){
	    	result.add(res[i]);
	    }
	    return result;
	}
	
	public int[] produce(int n) {
		int[] strArr=new int[(int) Math.pow(2, n)];
		if(n==1){
			strArr[0]=0;
			strArr[1]=1;
			return strArr;
		}
		int[] lastStrings=produce(n-1);		//当前n的格雷码 从 n-1的格雷码中产生
		for(int i=0;i<lastStrings.length;i++){
			strArr[i]=lastStrings[i];
			strArr[strArr.length-1-i]=(1<<(n-1))+lastStrings[i];
		}
		return strArr;
	}
}

  

 

转载于:https://www.cnblogs.com/271934Liao/p/7007626.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值