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.
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;
}
方法二、
505

被折叠的 条评论
为什么被折叠?



