Question:
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 - 001 - 111 - 310 - 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.
Ideas:
This is a very interesting question. At first glance, there is no way to do it, but it is easy to see the rules by listing the first few items:
N = 1:
0 (0)
1 (1)
N = 2:
00 (0)
01 (1)
11 (3)
10 (2)
N = 3:
000 (0)
001 (1)
011 (3)
010 (2)
110 (6)
111 (7)
101 (5)
100 (4)
It can be seen that each time n is added, the number of results doubles, and the first half is the same as n-1, the last half is actually the first half of the image symmetry, and then add 1 to the highest bit.
Therefore, we can use recursion to obtain n results through n-1. The Code is as follows:
public List<Integer> grayCode(int n) { List<Integer> result = new ArrayList<Integer>(); if(n<=1) { for(int i =0; i<=n; i++) { result.add(i); } return result; } result = grayCode(n-1); List<Integer> r1 = reverse(result); int x = 1<<(n-1); for(int i = 0; i< r1.size(); i++) { r1.set(i, r1.get(i)+x); } result.addAll(r1); return result; } public List<Integer> reverse(ArrayList<Integer> r) {List<Integer> result = new ArrayList<Integer>();for(int i = r.size()-1; i>=0; i--) {result.add(r.get(i));}return result; }
[Leetcode] Gray Code