题目:
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. 观察可以发现格雷码除了第一位外 格雷码是上下对称的,比如第一个格雷码与最后一个格雷码对称(除了第一位),第二个格雷码与倒数第二个对称,以此类推。
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; } }