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.
- Example 1:
Input: 2
Output: [0,1,3,2]
Explanation:
00 - 0
01 - 1
11 - 3
10 - 2
For a given n, a gray code sequence may not be uniquely defined.
For example, [0,2,3,1] is also a valid gray code sequence.
00 - 0
10 - 2
11 - 3
01 - 1 - Example 2:
Input: 0
Output: [0]
Explanation: We define the gray code sequence to begin with 0.
A gray code sequence of n has size = 2n, which for n = 0 the size is 20 = 1.
Therefore, for n = 0 the gray code sequence is [0].
解法
当n=0时,返回{0},当n=1时,返回{0,1}
当n==2时:
0 0-----0
0 1-----1
1 1-----3
1 0-----2
当n==3时:
0 0 0-----0
0 0 1-----1
0 1 1-----3
0 1 0-----2
1 1 0-----6
1 1 1-----7
1 0 1-----5
1 0 0-----4
由此可得n的数列为:n-1的数列加上n-1数列反过来排,并给每一个数加2的n-1次幂。
讲起来有点麻烦啊,还是偷个图吧
public List<Integer> grayCode(int n) {
return grayCodecore(n);
}
private List<Integer> grayCodecore(int n) {
// TODO Auto-generated method stub
List<Integer> list = new ArrayList<Integer>();
if (n == 0)
list.add(0);
else if (n == 1) {
Integer[] array = { 0, 1};
Collections.addAll(list, array);
} else {
list = grayCodecore(n - 1);
for (int i = list.size() - 1; i >= 0; i--)
list.add((int) (list.get(i) + Math.pow(2, n - 1)));
}
return list;
}
Runtime: 1 ms, faster than 44.03% of Java online submissions for Gray Code.
Memory Usage: 33 MB, less than 100.00% of Java online submissions for Gray Code.
解法二
Int Grey Code Binary Binary>>1
0 000 000 000
1 001 001 000
2 011 010 001
3 010 011 001
4 110 100 010
5 111 101 010
6 101 110 011
7 100 111 011
可见格雷码为i和i右移一位的异或
public List<Integer> grayCode(int n) {
List<Integer> list = new ArrayList<Integer>();
for(int i=0;i<Math.pow(2, n);i++)
list.add((i>>1)^i);
return list;
}
Runtime: 0 ms, faster than 100.00% of Java online submissions for Gray Code.
Memory Usage: 32.9 MB, less than 100.00% of Java online submissions for Gray Code.