[编程题]生成格雷码

[编程题] 生成格雷码

腾讯
在一组数的编码中,若任意两个相邻的代码只有一位二进制数不同, 则称这种编码为格雷码(Gray Code),请编写一个函数,使用递归的方法生成N位的格雷码。
给定一个整数n,请返回n位的格雷码,顺序为从0开始。
测试样例:
1
返回:["0","1"]

class GrayCode {
    vector<string> res;
public:
    vector<string> getGray(int n) {
        // write code here
        string s;
        getGrayCore(s,n);
        return res;
    }
    void getGrayCore(string&s,int n)
    {
        if(n==0) 
        {
            res.push_back(s);
            return;
        }
        s.push_back('0');
        getGrayCore(s,n-1);
        s.pop_back();
        
        s.push_back('1');
        getYargCore(s,n-1);
        s.pop_back();
    }
    void getYargCore(string&s,int n)
    {
        if(n==0) 
        {
            res.push_back(s);
            return;
        }
        s.push_back('1');
        getGrayCore(s,n-1);
        s.pop_back();
        
        s.push_back('0');
        getYargCore(s,n-1);
        s.pop_back();
    }
};
原文地址:https://www.cnblogs.com/learning-c/p/5740300.html