生成格雷码

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

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

测试样例:
1
返回:["0","1"]

 

class GrayCode {
    private:
      vector<string>res;
public:
    void gray(int i,int n,string& str)
        {
        int num=0,j=n-1;
        string s=str;
        if(i<(1<<n))
            num=i^(i>>1);
        else return;
        while(num!=0)
            {
            str[j]=num%2-0+'0';
            num=num/2;
            j--;
            
        }
        res.push_back(str);
        gray(i+1,n,s);
        
    }
    vector<string> getGray(int n) {
        // write code here
        if(n<=0) return res;
        string str="";
        for(int i=0;i<n;i++)
            str+='0';
        res.push_back(str);
        gray(1,n,str);
       return res;
    }
};

 

posted on 2016-03-20 09:50  RenewDo  阅读(172)  评论(0编辑  收藏  举报

导航