LeetCode OJ:Gray Code(格林码)

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

看着好像很难的样子,但是实际上就是一个二进制码到格林吗的转换而已,代码如下(这个本科的时候好像学过,但是不记得了,看了下别人的):

 1 class Solution {
 2 public:
 3     vector<int> grayCode(int n) {
 4         int total = 1 << n;
 5         vector<int> ret;
 6         for(int i = 0; i < total; ++i){
 7             ret.push_back(i>>1^i);    
 8         }
 9         return ret;
10     }
11 };

 java版本的代码如下所示:

 1 public class Solution {
 2     public List<Integer> grayCode(int n) {
 3         List<Integer> ret = new ArrayList<Integer>();
 4         int num = 1 << n;
 5         for(int i =0 ; i< num; ++i){
 6             ret.add(i>>1^i);
 7         }
 8         return ret;
 9     }
10 }

 

还有一种是总结规律的写法:

可以利用遞歸,在每一層前面加上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位元格雷碼產生的。
 
如果能夠理解上面的部分,下面部分的代碼實現就很容易理解了。
 1 public String[] GrayCode(int n) {
 2 
 3         // produce 2^n grade codes
 4         String[] graycode = new String[(int) Math.pow(2, n)];
 5 
 6         if (n == 1) {
 7             graycode[0] = "0";
 8             graycode[1] = "1";
 9             return graycode;
10         }
11 
12         String[] last = GrayCode(n - 1);
13 
14         for (int i = 0; i < last.length; i++) {
15             graycode[i] = "0" + last[i];
16             graycode[graycode.length - 1 - i] = "1" + last[i];
17         }
18 
19         return graycode;
20     }

 

posted @ 2015-11-21 16:34  eversliver  阅读(596)  评论(0编辑  收藏  举报