#include <iostream>
#include <vector>
using namespace std;
vector<string> func(size_t n){
vector<string> res{};
if(n == 0) return res;
if(n == 1){
res = {"0","1"};
return res;
}
res = func(n - 1);
vector<string> vStr;
for(auto s : res) vStr.push_back("0" + s);//纸上写的时候漏写了auto。。。
for(auto ps = res.end() - 1;ps >= res.begin();--ps){ //纸上写代码的时候居然写成 for(auto ps = res.end() - 1;i != res.begin();--i),真是太粗心了!!
string tem = *ps;
vStr.push_back("1" + tem);
}
return vStr;
}
int main(int argc, char *argv[])
{
for(auto s : func(5))
cout << s << endl;
return 0;
}
#include <iostream>
#include <vector>
using namespace std;
vector<string> func(size_t n){
vector<string> res{};
if(n == 0) return res;
size_t time = 1;
res.push_back("0");
res.push_back("1");
while(time++ < n){
size_t oldLen = res.size();
for(size_t t = oldLen - 1;t != -1;--t){
string tem = res[t];
tem = "1" + tem;
res.push_back(tem);
}
size_t newLen = res.size();
for(size_t i = 0;i != newLen / 2;++i)
res[i] = "0" + res[i];
}
return res;
}
int main(int argc, char *argv[])
{
for(auto s : func(3))
cout << s << endl;
return 0;
}
补充:
#include <iostream>
#include <vector>
using namespace std;
vector<int> getGrayCode(int n){
int num = 1 << n;
vector<int> res;
for(int i = 0; i != num;++i){
int tem = (i >> 1) ^ i;
res.push_back(tem);
}
return res;
}
int main(int argc, char *argv[])
{
for(auto i : getGrayCode(5))
printf("%x\n",i); //这种风格真丑,奈何C++输出16进制不方便,偷下懒~
return 0;
}