对于给定的正整数n,格雷码为满足如下条件的一个编码序列: (1) 序列由2^n个编码组成,每个编码都是长度为n的二进制位串。 (2) 序列中无相同的编码。 (3) 序列中位置相邻的两个编码恰有一位不同。 例如:n=2时的格雷码为:{00, 01, 11, 10}。
3
000 001 011 010 110 111 101 100
说明:通过递归打印其结果。
#include <cstdio> #include <cstring> using namespace std; typedef long long LL; void output(int* G, int lenth) { for (int i=0; i<lenth; i++){ printf("%d",G[i]); } printf("\n"); } void GeLeiMa(int* G, int index, int lenth) { if(index == lenth-1){ output(G, lenth); if (G[index] == 0) G[index] = 1; else G[index] =0; output(G, lenth); }else{ GeLeiMa(G, index+1, lenth); if (G[index] == 0) G[index] = 1; else G[index] = 0; GeLeiMa(G, index+1, lenth); } } int main() { int G[20]; int n; scanf("%d",&n); memset(G,0,sizeof(G)); GeLeiMa(G, 0, n); printf("\n"); return 0; }Grey序列的第i位为i xor (i>>1). 输出的是第i位格雷码的十进制形式。
n 二进制位数
n位的格雷码序列