class Solution {
//write down some cases, and try to find out the regular pattern
//gray code is not unique, so we should find out at least one regular pattern
//one of these regular pattern is that:
//let f(i) be the gray code sequence when n=i,
//then the number of sequence f(i+1) is twice of f(i), we consider f(i) is a half sequence of f(i+1)
//because the sequence f(i) is valid, so another half valid sequence can be find to add 1 in the highest bit of each element of f(i),
//the last thing we need to figure out is that we should concatenate these two sequence, the last one element of the second half will be
//only one digit different from the last of the first half, so we just need to reverse the second half
public:
vector<int> grayCode(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> ans;
ans.push_back(0);
for (int i = 1; i <= n; ++i)
{
int size = ans.size();
for (int j = size-1; j >= 0; --j)
ans.push_back( ans[j]^(1<<(i-1)) );
}
return ans;
}
};
second time
class Solution {
public:
vector<int> grayCode(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> ans(1);
ans[0] = 0;
int add = 1;
for(int i = 1; i <= n; ++i)
{
int oldSize = ans.size();
for(int j = oldSize-1; j >= 0; --j) ans.push_back(ans[j]+add);
add *= 2;
}
return ans;
}
};
本文详细介绍了灰码生成的原理与实现方法,通过构建有效的模式,利用递归思想和位运算技巧,实现了从任意长度到指定长度的灰码序列生成。包括核心算法解析、代码实现与验证过程。
387

被折叠的 条评论
为什么被折叠?



