题目描述
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.
样例输入 Copy
2
样例输出 Copy
00 01 11 10
#include <bits/stdc++.h>
using namespace std;
vector<string> f(int n)
{
if (n == 0) return vector<string>{"0"};
else if (n == 1) return vector<string>({ "0", "1" });
else
{
vector<string> newcode;
vector<string> code = f(n - 1);
for (auto it = code.begin(); it != code.end(); it++)
newcode.emplace_back("0" + *it);
for (auto it = code.rbegin(); it != code.rend(); it

该篇文章详细描述了如何使用C++编写一个递归函数来生成具有给定长度n的格雷码列表,适合于编程和算法学习者。
最低0.47元/天 解锁文章
1190

被折叠的 条评论
为什么被折叠?



