題目:
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].
解法1:
公式法:
格雷碼和對應的二進制有相應的轉換公式:二進制向右移一位然後再與自己異或就得到了對應的格雷碼
二進制 右移一位 異或 格雷碼 十進制數
00 00 00^00=00 00 0
01 00 00^01=01 01 1
10 01 01^10=11 11 3
11 01 01^11=10 10 2
c++:
class Solution {
public:
vector<int> grayCode(int n) {
vector<int> res;
int len = pow(2,n);
for(int i = 0; i < len; i++){
res.push_back((i >> 1) ^ i);
}
return res;
}
};
java:
class Solution {
public List<Integer> grayCode(int n) {
List<Integer> res = new ArrayList<Integer>();
int len = (int)Math.pow(2,n);
for(int i = 0; i < len; i++){
res.add((i >> 1) ^ i);
}
return res;
}
}
python:
class Solution(object):
def grayCode(self, n):
"""
:type n: int
:rtype: List[int]
"""
res = []
for i in xrange(2**n):
res.append((i>>1) ^ i)
return res
解法2:
動態規劃法
假設我們知道了n-1的格雷碼,我們如何得到n的格雷碼,n位的格雷碼比n-1的格雷碼多一位,這一位只有0和1兩種選擇
很簡單的策略就是在首位加上1和2,如下圖中間所示,但是我們發現不滿足格雷碼的定義,所以後面的要倒序排列,與上邊的成鏡像對稱
代碼的策略:
首先我們要給出n=0的初始情況,即0
然後循環n次,i從0到n-1,每次在前面加0相當於沒有變化,加1相當於加上2i,注意加1的要倒序排列
n=1 n =2(不正確) n=2
0 00 00
1 01 01
10 11
11 10
c++:
class Solution {
public:
vector<int> grayCode(int n) {
vector<int> res{0};
for(int i = 0; i < n; i++){
int add = 1 << i;
int len = res.size();
for(int j = len-1; j >= 0; j--){
res.push_back(res[j]+add);
}
}
return res;
}
};
java:
class Solution {
public List<Integer> grayCode(int n) {
List<Integer> res = new ArrayList<Integer>();
res.add(0);
for(int i = 0; i < n; i++){
int add = 1 << i;
int len = res.size();
for(int j = len-1; j >= 0; j--){
res.add(res[+add);
}
}
return res;
}
}
python:
class Solution(object):
def grayCode(self, n):
"""
:type n: int
:rtype: List[int]
"""
res = [0]
for i in xrange(n):
add = 1 << i;
size = len(res)
for j in xrange (size-1,-1,-1):
res.append(res[j] + add)
return res