在一组数的编码中,若任意两个相邻的代码只有一位二进制数不同, 则称这种编码为格雷码(Gray Code),请编写一个函数,使用递归的方法生成N位的格雷码。
给定一个整数n,请返回n位的格雷码,顺序为从0开始。
思想:
用递归法实现,把求n位格雷码分解为求n-1位格雷码的子问题,以及如何由n-1位格雷码构造n位格雷码的子问题。
第二个子问题,即依次遍历格雷码,在每一编码的末尾添加“0”或"1"。
用C++实现,如下代码
#include "stdafx.h" #include<vector> #include<iostream> #include<string> using namespace std; class GrayCode { public: vector<string> getGray(int n) { // write code here vector<string> ret = vector<string>(); if (n == 1) { ret.push_back("0"); ret.push_back("1"); return ret; } if (n <= 0) { ret.push_back("0"); return ret; } vector<string> post = getGray(n - 1); bool direction = true; for (vector<string>::iterator itr = post.begin(); itr != post.end(); itr++) { if (direction) { ret.push_back(*itr + "0"); ret.push_back(*itr + "1"); direction = false; } else { ret.push_back(*itr + "1"); ret.push_back(*itr + "0"); direction = true; } } return ret; } }; int main() { int n; while (true) { cout << "请输入格雷码(整数):" << endl; cin >> n; GrayCode gc = GrayCode(); vector<string> v = gc.getGray(n); for (vector<string>::iterator it = v.begin(); it != v.end(); it++) { cout << *it << endl; } } return 0; }
语言要点:
使用vector容器,vector<string> vs = vector<string>()定义容器;
vs.push_back()往容器末尾添加元素;
vector<string>::iterator 获得迭代器类型;
vector<string>::iterator it = vs.begin()得到迭代器头;
it != vs.end()判断迭代器是否还未结束;
it++将迭代器指向下一个元素;
*it 表示取迭代器当前指向的那个元素。