mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Update 89. Gray Code.md
This commit is contained in:
parent
f2cdd3f71b
commit
5c6ec02e23
@ -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位元的格雷码以上下镜射后加上新位元的方式快速的得到,如下图所示。
|
||||

|
||||
这样就可以用迭代的方式产生格雷码。
|
||||
|
||||
|
||||
|
||||
# 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;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
Loading…
Reference in New Issue
Block a user