LeetCode 89. Gray Code
Solution1:我的答案
穷举法,比较笨
注意:牢记vector中find()函数的用法
class Solution {
public:
vector<int> grayCode(int n) {
vector<int> res;
res.push_back(0);
int old_size = res.size();
while (1) {
old_size = res.size();
int last = *res.rbegin(); //temp是结果序列中的最后一个元素
int i = 0;
while (i < n) {
int temp = last;
temp = temp^(1 << i);//对指定位取反
if (find(res.begin(), res.end(), temp) == res.end()) {
res.push_back(temp);
break;
}
i++;
}
if (res.size() == old_size)
break;
}
return res;
}
};
补充知识:格雷码
参考网址:http://www.cnblogs.com/grandyang/p/4315649.html
格雷码是一种循环二进制单位距离码,主要特点是两个相邻数的代码只有一位二进制数不同的编码,格雷码的处理主要是位操作 Bit Operation,LeetCode中关于位操作的题也挺常见,比如 【187】Repeated DNA Sequences 求重复的DNA序列,【136】Single Number 单独的数字,和【137】Single Number II 单独的数字之二(【260】Single Number III不知道是不是关于格雷码的题…)等等。三位的格雷码和二进制数如下:
Int Grey Code Binary
0 000 000
1 001 001
2 011 010
3 010 011
4 110 100
5 111 101
6 101 110
7 100 111
Solution2:
其实这道题还有多种解法。首先来看一种最简单的,是用到格雷码和二进制数之间的相互转化,可参见我之前的博客 Convertion of grey code and binary 格雷码和二进制数之间的转换 ,明白了转换方法后,这道题完全没有难度,代码如下:
// Binary to grey code
class Solution {
public:
vector<int> grayCode(int n) {
vector<int> res;
for (int i = 0; i < pow(2, n); ++i) { //n个二进制位包含数字范围[0, 2^n-1],共有2^n个数
res.push_back((i >> 1) ^ i);
}
return res;
}
};
Solution3:
然后我们来看看其他的解法,参考维基百科上关于格雷码的性质,有一条是说镜面排列的,n位元的格雷码可以从n-1位元的格雷码以上下镜射后加上新位元的方式快速的得到,如下图所示一般。
有了这条性质,我们很容易的写出代码如下:
// Mirror arrangement
class Solution {
public:
vector<int> grayCode(int n) {
vector<int> res{0};
for (int i = 0; i < n; ++i) {
int size = res.size();
for (int j = size - 1; j >= 0; --j) {
res.push_back(res[j] | (1 << i));
}
}
return res;
}
};