Update 89. Gray Code.md

This commit is contained in:
唐树森 2019-03-21 23:35:37 +08:00 committed by GitHub
parent f2cdd3f71b
commit 5c6ec02e23
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -20,6 +20,11 @@ Int Grey Code Binary
```
参考维基百科及[这篇博客](http://www.omegaxyz.com/2017/11/16/grayandbi/)可很容易地写出代码。
## 思路三(最快)
参考[维基百科](https://zh.wikipedia.org/wiki/%E6%A0%BC%E9%9B%B7%E7%A0%81#%E9%8F%A1%E5%B0%84%E6%8E%92%E5%88%97)我们知道格雷码是按照镜面排列的n位元的格雷码可以从n-1位元的格雷码以上下镜射后加上新位元的方式快速的得到如下图所示。
![graycode](http://upload.wikimedia.org/wikipedia/commons/thumb/c/c1/Binary-reflected_Gray_code_construction.svg/250px-Binary-reflected_Gray_code_construction.svg.png)
这样就可以用迭代的方式产生格雷码。
# C++
@ -65,3 +70,24 @@ public:
}
};
```
## 思路三
``` C++
class Solution {
public:
vector<int> grayCode(int n) {
vector<int>res;
res.push_back(0);
for(int i = 0; i < n; i++){
int size = res.size();
for(int j = 0; j < size; j++)
res.push_back(res[size - j - 1]);
for(int j = 0; j < res.size(); j++){
res[j] = res[j] | ((j / size) << i); // 在左边添加一半的0和一半的1
// res[j] = (res[j] << 1) | (j / size); // 在右边添加一半的0和一半的1
}
}
return res;
}
};
```