长度为n的格雷码其实是在长度为n-1的末尾加0和1组成的,因此长度为n的格雷码有2^n个编码,以下用递归实现构造,从第n-1个构造到第n个时,n-1中第偶数位上先加0再加1,奇数位相反
class GrayCode {
public:
vector getGray(int n) {
// write code here
vector tmp;
if (n == 1) {
tmp.push_back("0");
tmp.push_back("1");
return tmp;
}
else {
vector tmp = getGray(n - 1);
vector ans;
for (int i = 0; i < (int)tmp.size(); i++) {
if (i & 1) {
ans.push_back(tmp[i] + "1");
ans.push_back(tmp[i] + "0");
}
else {
ans.push_back(tmp[i] + "0");
ans.push_back(tmp[i] + "1");
}
}
return ans;
}
}
};