生成格雷码

#include<iostream>
#include<string>
#include<vector>
#include<cmath>
using namespace std;
class GrayCode{
public:
	vector<string> getGray(int n){
		vector<string> res;
		if(n==1){
			res.push_back("0");
			res.push_back("1");
			return res;
		}
		vector<string> v = getGray(n-1);
		int len = pow(2.0,n-1);
		for(int i=0;i<len;i++){
			res.push_back("0"+v[i]);
		}
		for(int i=len-1;i>=0;i--){
			res.push_back("1"+v[i]);
		}
		return res;
	}
};
int main(){
	GrayCode code;
	int N;
	cin>>N;
	vector<string> res = code.getGray(N);
	int len = pow(2.0,N);
	for(int i =0;i<len;i++){
		cout<<res[i]<<endl;
	}
	return 0;
}

俩年没写过C++了,武功尽费的感觉,最近面试腾讯的时候遇到这样一道题,生成gray code,

网上看了一下别人的代码,然后自己模仿了一下,原理是利用递归来生成,并且gray码的规律是

N位的gray码前一半是:0"+"N-1位的grayCode",后一半是"0"+"N-1的grayCode"


然后类写好了,生成一个实例就ok,轮子造完,开始开车。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值