zoukankan      html  css  js  c++  java
  • [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;
    	}
    }
    

      

     

  • 相关阅读:
    ADO.NET Entity Framework 基本概述
    Team Fundation Server 2010 三
    Team Fundation Server 2010 一
    ADO.NET Data Services Framework 基础概述
    Git忽略已跟踪文件的改动
    菜单
    Eschool校园网平台介绍
    学习DDD与MVC系统架构的开源项目
    学校系统需求
    Firebird embed server
  • 原文地址:https://www.cnblogs.com/271934Liao/p/7007626.html
Copyright © 2011-2022 走看看