利用递归算法生成格雷码
#include <iostream>
#include <string>
#include <stack>
#include <stdlib.h>
std::stack<std::string> result;
static int count;
void generator() {
count--;
if (count > 0) {
generator();
std::stack<std::string> newResult;
int c = 0;
while(!result.empty()) {
std::string newA, newB;
newA = result.top();
result.pop();
if (!c) {
newB = newA + "0";
newResult.push(newB);
newB = newA + "1";
newResult.push(newB);
c = 1;
} else {
newB = newA + "1";
newResult.push(newB);
newB = newA + "0";
newResult.push(newB);
c = 0;
}
}
if (count % 2 == 0) {
while(!newResult.empty()) {
result.push(newResult.top());
newResult.pop();
}
} else
result = newResult;
} else {
result.push("1");
result.push("0");
}
}
int main() {
std::cin >> count;
generator();
while(!result.empty()) {
std::cout << result.top() << std::endl;
result.pop();
}
return 0;
}