Gray Code
题意是生成N位长的格雷码。格雷码是一种二进制的数值表示方法,两个连续值只有1位不同。例如,输入n=2,返回[0, 1, 3, 2]。对应的格雷码是这样的:
00 - 0 01 - 1 11 - 3 10 – 2
vector<int> grayCode(int n)
{
vector<int> vecRet;
stack<int> s;
if (n <= 0) return vector<int>(1, 0);
vecRet.push_back(0);
vecRet.push_back(1);
for (int i = 1; i < n; ++i)
{
int mask = 1 << i;
for (vector<int>::const_iterator it = vecRet.begin();
it != vecRet.end();
++it)
{
s.push(*it | mask);
}
while (!s.empty())
{
vecRet.push_back(s.top());
s.pop();
}
}
return vecRet;
}