標籤:
題目:
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.
原始思路:利用卡諾圖產生2進位的格雷碼,再轉化為十進位。
卡諾圖原理:利用卡諾圖相鄰兩格只有一位變化以及卡諾圖的變數取值以低階格雷碼的順序排布的特徵,可以遞迴得到高階格雷碼。由於此方法相對繁瑣,使用較少。產生格雷碼的步驟如下:
- 將卡諾圖變數分為兩組,變數數目相近(最好相等)
- 以邏輯變數高位在左低位在右建立卡諾圖
- 從卡諾圖的左上方以之字形到右上方最後到左下角遍曆卡諾圖,依次經過格子的變數取值即為典型格雷碼的順序
三位格雷碼(三位格雷碼由建立在二位基礎上)
| AB╲ C |
0 |
1 |
| 00 |
0→ |
1↓ |
| 01 |
↓2 |
←3 |
| 11 |
6→ |
7↓ |
| 10 |
4 |
←5 |
格雷碼次序:000
起點→001
→011
→010
→110
→111→101
→100
終點四位格雷碼
| AB╲CD |
00 |
01 |
11 |
10 |
| 00 |
0→ |
1→ |
3→ |
2↓ |
| 01 |
↓4 |
←5 |
←7 |
←6 |
| 11 |
12→ |
13→ |
15→ |
14↓ |
| 10 |
8 |
←9 |
←11 |
←10 |
原始代碼:
public class Solution { public List<Integer> grayCode(int n) { List<Integer> req = new ArrayList<Integer>(); String[] gray = factory(n); for(int i = 0 ; i < gray.length ; i++){ String temp = gray[i]; int toInt = binaryToInt(temp); req.add(toInt); } return req; } public String[] factory(int n){ //建立格雷碼 String[] req = new String[(int)Math.pow(2, n)]; if( n == 0){ req[0] = "0"; return req; } if( n == 1){ req[0] = "0"; req[1] = "1"; return req; } int up = n/2; //小 int left = n - up; //大 String[] upStr = factory(up); String[] leftStr = factory(left); int len = 0; for(int i = 0 ; i < leftStr.length ; i++){ for(int j = 0 ; j < upStr.length ; j++){ req[len] = leftStr[i] + upStr[j]; len++; } i++; for(int j = upStr.length-1 ; j >= 0 ; j--){ req[len] = leftStr[i] + upStr[j]; len++; } } return req; } public int binaryToInt(String str){ //2進位轉化為十進位 int count = 0; int len = str.length(); for(int i = 0 ; i < len ; i++){ int temp = str.charAt(i) - ‘0‘; if(temp == 0) continue; else count += (int)Math.pow(2,len-1-i); } return count; }}
改進思路:利用新的產生原理,可以看到n位的格雷碼由兩部分構成,一部分是n-1位格雷碼,再加上 1<<(n-1)和n-1位格雷碼的逆序(整個格雷碼逆序0132變成2310這種)的和。
原文連結:http://www.cnblogs.com/springfor/p/3889222.html?utm_source=tuicool
改進代碼:
public class Solution { public List<Integer> grayCode(int n) { if(n==0){ List<Integer> req = new ArrayList<Integer>(); req.add(0); return req; } List<Integer> req = grayCode(n-1); int addNumber = 1<<n-1; int preSize = req.size(); for(int i = preSize-1 ; i>=0 ; i--){ req.add(addNumber + req.get(i)); } return req; }}
[LeetCode-JAVA] Gray Code