<LeetCode OJ> 89. Gray Code

Total Accepted: 59678  Total Submissions: 164093  Difficulty: Medium

The gray code is a binary numeral system wheretwo successive values differ in only one bit.

Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. 

A gray code sequence must begin with 0.

For example, given n = 2, return [0,1,3,2]. Its gray code sequence is:

00 - 0
01 - 1
11 - 3
10 - 2

Note:
For a given n, a gray code sequence is not uniquely defined.

For example, [0,2,3,1] is also a valid gray code sequence according to the above definition.

For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that.

Subscribe to see which companies asked this question

Hide Tags
  Backtracking

分析:

TMD,找了半天规律才看出规律来!感觉此题好蛋疼。

格雷码的生成规则:

当是第奇数个的格雷码时(从0开始算,显然全零的就是第0个),只需要改变他的上一个格雷码最左边的位元即可

当是第偶数个格雷码时,只需从从最右边开始找到第一个1位元,逆置他的左边位元即可

class Solution {
public:
    int gray2num(vector<int> &Gray, int nBits)//nBits位的格雷码转换成对应的数字
    {
    	int ans = 0;
    	for (int i = 0; i < nBits; i++)
    		ans += Gray[i] * pow(2,nBits-i-1);
    	return ans;
    }
    void GrayCode(int nBits)
    {
    	int graynums = pow(2, nBits);
    	vector<int> Gray(nBits,0);
    	result.push_back(gray2num(Gray, nBits));//全0,此时就是第一个格雷码
    	for (int j = 1; j< graynums; j++){
    		if (j % 2 == 1)//奇数时格雷码生成规则
    		{
    			Gray[nBits - 1] = changeBit(Gray[nBits - 1]);//此时只需逆置最左边的位元即可
    			result.push_back(gray2num(Gray, nBits));
    		}
    		else//偶数时的格雷码生成规则
    		{
    			for (int j = nBits - 1; j >= 0; j--){//从最右边开始找,找到第一个1,逆置他左边的位元
    				if (Gray[j] == 1){
    					Gray[j - 1] = changeBit(Gray[j - 1]);
    					break;
    				}
    			}
    			result.push_back(gray2num(Gray, nBits));
    		}
    	}
    }
    int changeBit(int a)//位的变换
    {
    	return a == 0 ? 1 : 0;
    }
    vector<int> grayCode(int n) {
        GrayCode(n);
        return result;
    }
private:
    vector<int> result;
};


学习别人的:

格雷码序列生成问题,序列中前后连续的两个数的二进制只有一位比特位不同,用下面这张图表示: 
这里写图片描述 

格雷码有个公式,自然整数n对应的格雷码为:
n ^ (n/2)
源码

class Solution {
public:
    // 格雷码数学公式:整数n的格雷码为: n^(n >> 1)
    // 现在要生成所有n比特的格雷码
    vector<int> grayCode(int n) {
        vector<int> ret;
        size_t size = 1 << n ;//2^n个自然数
        for(size_t i = 0; i < size; i++){
            ret.push_back(i ^ (i >> 1));
        }
        return ret;
    }
};



参考博客:Johnkui

http://blog.csdn.net/Johnkui/article/details/51171327


注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!

原文地址:http://blog.csdn.net/ebowtang/article/details/51290384

原作者博客:http://blog.csdn.net/ebowtang

本博客LeetCode题解索引:http://blog.csdn.net/ebowtang/article/details/50668895

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值