[leetcode] 89.Gray Code

题目:
The gray code is a binary numeral system where two 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.
题意:
本题是关于格雷码的实现的,相邻的两个数字的二进制位只有一位不同。
思路:
使用递归的解法:

  1. 1位格雷码有两个码字
  2. (n+1)位格雷码中的前2n个码字等于n位格雷码的码字,按顺序书写,加前缀0
  3. (n+1)位格雷码中的后2n个码字等于n位格雷码的码字,按逆序书写,加前缀1
    分析此递归过程:
    其实这个递归定义的思路还是很明显的。比如说一共有三位,即n=3。考虑只有一位的情况,毋庸置疑,前两个数字分别是0,1;这个时候考虑将位数增加1,此时一共有两位,因为前两个数字是00,01,那么接下来变化的是将第二位的0变成1,而第一位的值是只有一位时的最后一个,即此刻接下来的数是11,然后接着是10。当将位数提高到三位时,前四位就是000,001,011,010,接下来的4位是需要将最前面的0变成1的,很明显,后两位的值的顺序应该是10,11,01,00,因为010的下一位是110(改变第三位上的数从0到1),而格雷码的特点是每两个相邻的数只差一位上的数字,所以当最高位是1的时候,后两位的变化就是刚才求的只有两位时的一个倒序。
    以上。
    代码如下:
class Solution {
public:
    vector<int> grayCode(int n) {
        vector<int> result; 
        result.push_back(0);
        if(n == 0)return result;
        result.push_back(1);
        int num_2_n = 1;
        for(int i = 1; i < n; i++){
            num_2_n *= 2;
            for(int i = num_2_n - 1; i >= 0; i--)
                result.push_back(num_2_n + result[i]);
        }
        return result;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值