From 5c6ec02e232b51d3697c390962bcb07adc21653d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=94=90=E6=A0=91=E6=A3=AE?= Date: Thu, 21 Mar 2019 23:35:37 +0800 Subject: [PATCH] Update 89. Gray Code.md --- solutions/89. Gray Code.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/solutions/89. Gray Code.md b/solutions/89. Gray Code.md index 56c2945..d1b89f7 100644 --- a/solutions/89. Gray Code.md +++ b/solutions/89. Gray Code.md @@ -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 grayCode(int n) { + vectorres; + 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; + } +}; +```