题目:T he gray code is binary numeral system where two successive values differ in only one bit.
Given a non-negative interger 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-1
10-2
Note:
别人的解法:
为了理解这个问题,我们可以想象每个数表示的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维,如果可以形成一个递归问题,
最终简化为即1->0与0->1两种。
#include <iostream>
using namespace std;
//grey
//精简版
class Solution {
public :
vector <int> greyCode (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;
}
};
记了个别人的方法,我来想想自己的方法、