#include<iostream>
#include<string>
#include<vector>
#include<cmath>
using namespace std;
class GrayCode{
public:
vector<string> getGray(int n){
vector<string> res;
if(n==1){
res.push_back("0");
res.push_back("1");
return res;
}
vector<string> v = getGray(n-1);
int len = pow(2.0,n-1);
for(int i=0;i<len;i++){
res.push_back("0"+v[i]);
}
for(int i=len-1;i>=0;i--){
res.push_back("1"+v[i]);
}
return res;
}
};
int main(){
GrayCode code;
int N;
cin>>N;
vector<string> res = code.getGray(N);
int len = pow(2.0,N);
for(int i =0;i<len;i++){
cout<<res[i]<<endl;
}
return 0;
}
俩年没写过C++了,武功尽费的感觉,最近面试腾讯的时候遇到这样一道题,生成gray code,
网上看了一下别人的代码,然后自己模仿了一下,原理是利用递归来生成,并且gray码的规律是
N位的gray码前一半是:0"+"N-1位的grayCode",后一半是"0"+"N-1的grayCode"
然后类写好了,生成一个实例就ok,轮子造完,开始开车。