您的位置:首页 > 其它

89. Gray Code

2016-05-23 09:16 357 查看
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的格雷码有4个:00,01,11,10, (即:0,1,3,2);则存在这样的关系,长度为3的格雷码有8个,前4个是 0-00, 0-01, 0-11, 0-10,(即:0,1,3,2), 后四个是:1-00,1-01,1-11,1-10。就是在前一个长度的格雷码表示上前半段加上0(表示的数值不变),后半段加上1即可。对于从长度n-1到长度到n的变化过程也符合这个规律。

class Solution {
public:
vector<int> grayCode(int n) {
vector<int> res(1<<n, 0);
int count = 1;
for (int i = 1; i <= n; i++){
int count = 0;
for (int j = (1<<i)-1; j > (1<<i-1)-1; j--){
res[j] = res[count++] | 1 << i-1;
}
}
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: