Gray Code

一. 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.

Difficulty:Medium

TIME:7MIN

解法一(循环求解)

第一种思路是采用格雷码的对称机制

/*
1位格雷码
0 -- 0
1 -- 1

2位格雷码
00 -- 0
01 -- 1
11 -- 3(2 + 1)
10 -- 2(2 + 0)
可以发现最右边一位是对称的

3位格雷码
000 -- 0
001 -- 1
011 -- 3
010 -- 2
110 -- 6(4 + 2)
111 -- 7(4 + 3)
101 -- 5(4 + 1)
100 -- 4(4 + 0)
可以发现最右边两位是对称的
*/

因此就可以采用这种对称的方法求出所有的格雷码。

vector<int> grayCode(int n) {
    vector<int> result{0};
    vector<int> v(n, 1);
    for(int i = 1; i < n; i++) //2的k次方,放在数组中避免多次求解
        v[i] = 2 * v[i - 1];
    for(int i = 0; i < n; i++) {
        for(int k = result.size() - 1; k >= 0; k--) {
            result.push_back(v[i] + result[k]);
        }
    }
    return result;
}

代码的时间复杂度为 O(2n)

解法二(直接求解)

这道题是求格雷码的序列,如果单独要求第n位格雷码,又要如何求解呢

/*
给定数字n
对应的第n + 1位格雷码有(n >> 1) ^ n

比如对于5
5 >> 1 = 2
2 -- 010
5 -- 101
2 ^ 5 = 111 = 7 刚好是第6位格雷码
*/

因此代码如下:

vector<int> grayCode(int n) {
    vector<int> result;
    int len = 1 << n;
    for(int i = 0; i < len ; i++) {
        result.push_back((i >> 1) ^ i);
    }
    return result;
}

代码的时间复杂度为 O(2n)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值