生成格雷碼

在一組數的編碼中,若任意兩個相鄰的代碼只有一位二進制數不一樣, 則稱這種編碼爲格雷碼(Gray Code),請編寫一個函數,使用遞歸的方法生成N位的格雷碼。ios

給定一個整數n,請返回n位的格雷碼,順序爲從0開始。函數

 

思想:post

 

用遞歸法實現,把求n位格雷碼分解爲求n-1位格雷碼的子問題,以及如何由n-1位格雷碼構造n位格雷碼的子問題。編碼

 

第二個子問題,即依次遍歷格雷碼,在每一編碼的末尾添加「0」或"1"。spa

用C++實現,以下代碼code

#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;
}

 

語言要點:blog

使用vector容器,vector<string> vs = vector<string>()定義容器;遞歸

vs.push_back()往容器末尾添加元素;ci

vector<string>::iterator 得到迭代器類型;get

vector<string>::iterator it = vs.begin()獲得迭代器頭;

it != vs.end()判斷迭代器是否還未結束;

it++將迭代器指向下一個元素;

*it 表示取迭代器當前指向的那個元素。

相關文章
相關標籤/搜索