mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
update solution 3
This commit is contained in:
parent
b01ab44ea0
commit
9d31289601
@ -21,9 +21,9 @@ 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位元的格雷码以上下镜射后加上新位元的方式快速的得到,如下图所示。
|
||||
参考[维基百科](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位元的格雷码以上下镜射后加上新位元的方式快速的得到,如下图所示。
|
||||

|
||||
这样就可以用迭代的方式产生格雷码。
|
||||
可以在前面加上新位元(如上图绿色所示),这样就和思路二产生的一样了;也可以在后面添加新位元,也是满足要求的(相邻两个编码只有一个bit不同)。
|
||||
|
||||
|
||||
|
||||
@ -76,15 +76,19 @@ public:
|
||||
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
|
||||
vector<int>res{0};
|
||||
for(int b = 0; b < n; b++){
|
||||
for(int i = res.size() - 1; i >= 0; i--) // 镜面复制
|
||||
res.push_back(res[i]);
|
||||
|
||||
int half_size = res.size() >> 1;
|
||||
for(int i = 0; i < half_size; i++){
|
||||
// 在前面添加新位元
|
||||
res[i + half_size] += (1 << b);
|
||||
|
||||
// 在后面添加新位元
|
||||
// res[i] <<= 1;
|
||||
// res[i + half_size] = (res[i + half_size] << 1) + 1;
|
||||
}
|
||||
}
|
||||
return res;
|
||||
|
Loading…
Reference in New Issue
Block a user