笔试题13. 格雷码

来源:互联网 发布:xcode c语言图形界面 编辑:程序博客网 时间:2024/06/17 00:48

问题描述:在一组数的编码中,若任意两个相邻的代码只有一位二进制数不同, 则称这种编码为格雷码(Gray Code),请编写一个函数,使用递归的方法生成N位的格雷码。

给定一个整数n,请返回n位的格雷码,顺序为从0开始。

测试样例:
1
返回:["0","1"]
看到这个题的时候大脑里面马上想到是递归,于是就想出了下面的代码:
#include <iostream>#include <vector>#include <string>using namespace std;class GrayCode {public:vector<string> getGray(int n) {// write code here string str; retGary(_gary,str, n); return _gary;}void Print(vector<string> gary){vector<string>::iterator _it = gary.begin();cout << "[";for (; _it != gary.end() - 1; ++_it){cout << "\"" << _it->c_str() << "\"" << ",";}cout << "\"" << _it->c_str() << "\"";cout << "]";}protected:void retGary(vector<string> &gary,string gary_str, int n){if (n == 0){gary.push_back(gary_str);return;}gary_str += "0";retGary(gary,gary_str, n-1);gary_str.pop_back();gary_str += "1";retGary(gary,gary_str, n-1);}private:vector<string> _gary;};int main(){GrayCode G;vector<string> tmp = G.getGray(3);G.Print(tmp);return 0;}


感觉还可以的,好像和题目要求差不多,但是仔细看看,它并不满足“格雷码”的要求-------》若任意两个相邻的代码只有一位二进制数不同。
哎,再想想呗。要想满足条件,必须要一些策略吧。
     //( 0  1) -- (00  01  11  10)  --- ( 000  001  011  010  110  111  101  100)
原来是这样的,n 位格雷码跟(n-1)位格雷码有关系,后面的等于前面的依次从头到尾在第一位加上“0”,然后再尾到头加上 “1”。
#include <iostream>#include <vector>#include <string>using namespace std;class GrayCode {public:vector<string> getGray(int n){vector<string> gary;if (n == 1){gary.push_back("0");gary.push_back("1");return gary;}vector<string> prevGary = getGray(n - 1);for (int i = 0; i < prevGary.size(); ++i){gary.push_back("0" + prevGary[i]);}for (int j = prevGary.size() - 1; j >= 0; --j){gary.push_back("1" + prevGary[j]);}return gary;}void Print(vector<string> gary){vector<string>::iterator _it = gary.begin();cout << "[";for (; _it != gary.end() - 1; ++_it){cout << "\"" << _it->c_str() << "\"" << ",";}cout << "\"" << _it->c_str() << "\"";cout << "]";}};int main(){GrayCode G;vector<string> tmp = G.getGray(3);G.Print(tmp);return 0;}


                                             
0 0
原创粉丝点击