LeetCode 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
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.
本题以格雷码为引子,有两种解法,一种是寻找格雷码变化规律,然后模拟变化过程,得出结果;另一种是用异或。
方法一:模拟
例如当n=2时,格雷码如下:
00
01
11
10
当n=3时,格雷码
000
001
011
010
110
111
101
100
由以上可以看到规律:n的格雷码由n-1格雷码推导出来。在n-1格雷码左边加个0,以及在n-1的格雷码最左边加个1,然后把n-1个格雷码逆序。时间复杂度O(n^2)
根据以上规律写出代码
vector<int> grayCode(int n)
{
vector<int> res;
res.push_back(0);
//从0--n逐个添加到res中
for (int i = 0; i < n; i++)
{
//左移一位,相当于h = 2^i,也就是格雷码的 1*******,因为0******已经保存在res中了
int h = 1 << i;
int len = res.size();
//逆序添加,根据以往保存在res中的数据再加上1******就是要添加的
for (int j = len-1; j >= 0; j--)
{
res.push_back(h + res[j]);
}
}
return res;
}
方法二、
运用格雷码和二进制的转换,参考
时间效率高。