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==4时,观察规律:
0.1.3.2.6.7.5.4.12.13.15.14.10.11.9.8
0.1 加1
3.2 上面的0. 1从右开始一次加2,得到0.1.3.2
0.1.3.2 这四个数依次加4得到 4 5 7 6 倒置,6 7 5 4 添加到末尾 0.1.3.2.6.7.5.4.
0.1.3.2.6.7.5.4. 依次加8, 8.9.11.10.14.15.13.12倒置,12.13.15.14.10.11.9.8.添加到末尾 得到0.1.3.2.6.7.5.4.12.13.15.14.10.11.9.8
class Solution {
public:
vector<int> grayCode(int n) {
vector<int> res(1,0);
for(int i=0;i<n;i++)
{
int size=res.size();
while(size)
{
size--;
int cur=res[size];
cur+=1<<i;
res.push_back(cur);
}
}
return res;
}
};