LeetCode89——Gray Code
通过二进制和递归两种方式求解n位生成格雷码(十进制表示)..
原题
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
二进制生成格雷码
首先是比较简单的“平民”算法,之前学过数字电路应该有相关的内容:
第i位格雷码的生成公式为:
即对应二进制相邻位的异或,其中计算时在二进制的最高位之前补0。
二进制与格雷码表如图所示:
二进制到格雷码转换示意图:
由此本题的基本步骤思路为:
1. n位二进制数可表示2n个十进制数0−(2n−1),根据此将这些十进制分别转换为二进制。
2. 由二进制数转换为格雷码
3. 格雷码生成十进制数(按照二进制数转十进制数的方法进行)
代码:
比较繁琐,但相对比较好理解。
class Solution {
private:
int binary2grey(vector<int>binary)
{
vector<int>greyCode;
for (int i = 0; i < binary.size() - 1; i++)
{
greyCode.push_back(binary[i] ^ binary[i + 1]);
}//二进制到格雷码
int sum = 0;
for (int i = greyCode.size() - 1; i >= 0; i--)
{
sum += greyCode[i] << (greyCode.size() - 1 - i);
}//格雷码到十进制
return sum;
}
vector<int> num2Binary(int nums)//十进制转二进制
{
vector<int>result;
while (nums)
{
result.insert(result.begin(), nums % 2);
nums /= 2;
}
result.insert(result.begin(), 0);
return result;
}
public:
vector<int> grayCode(int n) {
int bits = pow(2, n);
vector<int>result;
//num2Binary(6);
for (int i = 0; i < bits; i++)
{
vector<int>binary = num2Binary(i);//十进制转二进制
int grey = binary2grey(binary);//二进制->格雷码->十进制
result.push_back(grey);//写入结果
}
return result;
}
};
格雷码的递归求解
根据格雷码的特性,可以知道欲求n位生成格雷码,必须用到n-1位生成格雷码
其规律是:
n位生成格雷码的前2n−1项即为n-1位生成格雷码的2n−1项,并在最高位之前补0;
n位生成格雷码的前2n−1项即为n-1位生成格雷码的2n−1项的逆序,并在最高位之前补1。
例如:
2位生成格雷码为:
00
01
11
10
按照上述规律:
3为生成格雷码的前4项为:
000
001
011
010
后4项为:
110
111
101
100
8项依次按顺序即为所求结果(注意是对称的)。
因此使用递归求解:
代码:
class Solution {
public:
vector<int> grayCode(int n) {
vector<int>gray;
if (n == 0)
{
gray.push_back(0);
//gray.push_back(1);
return gray;
}
vector<int> preGray = grayCode(n - 1);
vector<int>resGray(preGray);//前 2^(n-1)个数
for (int i = preGray.size() - 1; i >= 0; i--)
{
int temp = preGray[i] + pow(2, n - 1);
resGray.push_back(temp);
}//后2^(n-1)个数
return resGray;
}
};