Gray Code

来源:互联网 发布:广告单页设计软件 编辑:程序博客网 时间:2024/06/16 11:05

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 - 111 - 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.

格雷码就是二进制表示每次比之前的变化一位。初始化前两位为0,1.将其反转加上

2,得到下一个结果0,1,3,2,在反转加上4,依次类推得到结果。

public ArrayList<Integer> grayCode(int n) {ArrayList<Integer> result = new ArrayList<Integer>();if (n <= 1) {for (int i = 0; i <= n; i++)result.add(i);return result;}result = grayCode(n - 1);ArrayList<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 ArrayList<Integer> reverse (ArrayList<Integer> r) {ArrayList<Integer> rev = new ArrayList<Integer>();for (int i = r.size() - 1; i >= 0; i--) rev.add(r.get(i));return rev;}
另一种结果可以设置0,2,3,1得到,只是目前leetcode不识别这种结果。

但是我认为测试是通过的。

public List<Integer> grayCode1(int n) {List<Integer> result=new ArrayList<Integer>();if(n==0){result.add(0);return result;}if(n==1){result.add(0);result.add(2);return result;}if(n==2){result.add(0);result.add(2);result.add(3);result.add(1);return result;}result=grayCode1(n-1);List<Integer> at=reverse(result);int x=1<<(n-1);for(int i=0;i<at.size();i++)at.set(i,at.get(i)+x);result.addAll(at);return result;}


0 0
原创粉丝点击