[LintCode] Gray Code 格雷码

时间:2022-05-31 23:27:43

The gray code is a binary numeral system where two successive values differ in only one bit.

Given a non-negative integer n representing the total number of bits in the code, find the sequence of gray code. A gray code sequence must begin with 0 and with cover all 2nintegers.

Notice

For a given n, a gray code sequence is not uniquely defined.

[0,2,3,1] is also a valid gray code sequence according to the above definition.

Have you met this question in a real interview?
Yes
Example

Given n = 2, return [0,1,3,2]. Its gray code sequence is:

00 - 0
01 - 1
11 - 3
10 - 2
Challenge

O(2n) time.

LeetCode上的原题,请参见我之前的博客Gray Code

解法一:

class Solution {
public:
/**
* @param n a number
* @return Gray code
*/
vector<int> grayCode(int n) {
vector<int> res;
for (int i = ; i < pow(, n); ++i) {
res.push_back((i >> ) ^ i);
}
return res;
}
};

解法二:

class Solution {
public:
/**
* @param n a number
* @return Gray code
*/
vector<int> grayCode(int n) {
vector<int> res{};
for (int i = ; i < n; ++i) {
int size = res.size();
for (int j = size - ; j >= ; --j) {
res.push_back(res[j] | ( << i));
}
}
return res;
}
};

解法三:

class Solution {
public:
/**
* @param n a number
* @return Gray code
*/
vector<int> grayCode(int n) {
vector<int> res{};
int len = pow(, n);
for (int i = ; i < len; ++i) {
int pre = res.back();
if (i % == ) {
pre = (pre & (len - )) | (~pre & );
} else {
int cnt = , t = pre;
while ((t & ) != ) {
++cnt; t >>= ;
}
if ((pre & ( << cnt)) == ) pre |= ( << cnt);
else pre &= ~( << cnt);
}
res.push_back(pre);
}
return res;
}
};

解法四:

class Solution {
public:
/**
* @param n a number
* @return Gray code
*/
vector<int> grayCode(int n) {
vector<int> res{};
unordered_set<int> s;
stack<int> st;
s.insert();
st.push();
while (!st.empty()) {
int t = st.top(); st.pop();
for (int i = ; i < n; ++i) {
int k = t;
if ((k & ( << i)) == ) k |= ( << i);
else k &= ~( << i);
if (s.count(k)) continue;
s.insert(k);
st.push(k);
res.push_back(k);
break;
}
}
return res;
}
};

解法五:

class Solution {
public:
/**
* @param n a number
* @return Gray code
*/
vector<int> grayCode(int n) {
vector<int> res;
unordered_set<int> s;
helper(n, s, , res);
return res;
}
void helper(int n, set<int>& s, int out, vector<int>& res) {
if (!s.count(out)) {
s.insert(out);
res.push_back(out);
}
for (int i = ; i < n; ++i) {
int t = out;
if ((t & ( << i)) == ) t |= ( << i);
else t &= ~( << i);
if (s.count(t)) continue;
helper(n, s, t, res);
break;
}
}
};