题目:
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维空间中的点,二进制中的每一位就是一个维度。例如,n=2时,我们得到的是00,01,11,10这样的一个二维的正方形;n=3时,我们得到的是一个立方体。题目中的变化条件可以解释为每次只能在某个维度上做一个移动(1->0或0->1),最终的答案代表着用一条路径遍历整个n维图形的所有顶点。总体来说有两个思路: 思路一:每次改变一个维度,例如三维平面中依次改编1,2,3,2,1,2,3,不过此方法不能被LeetCode的测试数据所接受。 思路二:遍历n维平面的过程为,从n维的某个数出发,保持最高维度不变的情况下,遍历n-1维;再取出n-1维遍历后的最后一位,将其最高位改变,然后再保持最高维度不变遍历n-1维。如果可以形成一个递归问题,最终简化为1维即1->0与0->1两种情况。
代码:
思路一:
class Solution {
public:
vector<int> grayCode(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> v;
if(n <=0 )
{
v.push_back(0);
return v;
}
else if(n == 1)
{
v.push_back(0);
v.push_back(1);
return v;
}
v.push_back(0);
int pre = 0;
int dim = 1;
bool increase = true;
int run = 0;
int total = pow(2, n);
while(run < total-1)
{
pre = createCode(pre, dim);
v.push_back(pre);
run++;
if(dim == n)
{
increase = false;
dim--;
}
else if(dim == 1)
{
increase = true;
dim++;
}
else
{
dim = increase?dim+1:dim-1;
}
};
return v;
}
int createCode(int pre, int dim)
{
int tmp = 1;
while(dim > 1)
{
tmp *= 2;
dim -= 1;
}
if(pre / tmp % 2 == 0)
{
pre += tmp;
}
else
{
pre -= tmp;
}
return pre;
}
};
思路二:
class Solution {
public:
vector<int> result;
vector<int> grayCode(int n) {
int cur = 0;
result.push_back(cur);
grayChange(cur, n);
return result;
}
void grayChange(int &cur, int dim){
if(dim == 0){
return;
}
if(dim > 1){
grayChange(cur, dim - 1);
}
if((cur >> (dim - 1)) % 2 == 0){
cur += 1 << (dim - 1);
}
else{
cur -= 1 << (dim - 1);
}
result.push_back(cur);
if(dim > 1){
grayChange(cur, dim - 1);
}
}
};
精简版
class Solution {
public:
vector<int> grayCode(int n) {
vector<int> results;
if (n == 0)
{
results.push_back(0);
}
else if(n > 0)
{
results = grayCode(n-1);
int length = results.size();
for (int i = length -1 ; i >=0 ; i--)
{
results.push_back(results[i] + (1<<(n-1)));
}
}
return results;
}
};