题目描述
A Gray code is a list of all 2^n bit strings of length n, where any two successive strings differ in exactly one bit (i.e., their Hamming distance is one).
Your task is to create a Gray code for a given length n.
输入
The only input line has an integer n(1 ≤ n ≤ 16).
输出
Print 2^n lines that describe the Gray code. You can print any valid solution.
样例输入
复制
2
样例输出
复制
00 01 11 10
生成格雷码(Gray Code)有一个经典的递归构造方法,利用了格雷码的自相似特性。以下是具体实现思路和代码:
核心思路
格雷码的构造规律:
- 当
n=1
时,格雷码为0
、1
- 当
n>1
时,可通过以下步骤构造:- 生成
n-1
位的格雷码序列 - 将该序列反向排列
- 在原序列的每个元素前 加
0
- 在反向序列的每个元素前 加
1
- 拼接这两个序列,得到
n
位的格雷码
- 生成
代码
cpp
#include<bits/stdc++.h>
using namespace std;
int n;
vector<string> who(int x){
if(x==1)return{"0","1"};
vector<string>pre=who(x-1);
vector<string>ok;
for(auto &i:pre)ok.push_back("0"+i);
for(int i=pre.size()-1;i>=0;--i)
ok.push_back("1"+pre[i]);
return ok;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cin>>n;
vector<string>ans=who(n);
for(auto &i:ans){
cout<<i<<'\n';
}
return 0;
}