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.

分析:

n=3时的格雷码如下:

000
001
011
010

----------对称轴

110
111
101
100
前4个最高位是0,而后4个最高位是1
将上述格雷码的最高位去掉,观察剩下的2位:前4个恰好是n=2的格雷码,而后4个是前4个的逆序。
因此,我们将格雷码看成是上下两部分,如下图:


上半部分是n=2的格雷码(最高位多了一个0,但这对结果并没有影响);
下半部分是n=2的格雷码的逆序,然后在最高位加1(本例中,最高位加1 等价于 将格雷码加4)

python代码1:

class Solution(object):
    def grayCode(self, n):
        """
        :type n: int
        :rtype: List[int]
        """
        if n==0:
            return [0]
        self.sequence=[0,1]
        if n==1:
            return self.sequence
        for i in [2**x for x in range(1,n)]:
            self.sequence.extend([i+v for v in self.sequence[::-1]])
            #或者使用sequence[None:None:-1],表示通过切片获得列表sequence的反向副本,切片操作不改变列表sequence本身
        return self.sequence

Python代码2:

class Solution(object):
    def grayCode(self, n):
        """
        :type n: int
        :rtype: List[int]
        """
        self.sequence=[0]
        for i in [1<<x for x in range(n)]:# 1<<x 等价于 2的x次方
            self.sequence.append(self.sequence[-1]+i)
            self.sequence.extend([i+v for v in self.sequence[-3::-1]])
        return self.sequence

C++代码:

class Solution {
public:
    vector<int> grayCode(int n) {
        vector<int>sequence;
        sequence.push_back(0);
        for(int i=0;i<n;i++)
        {
            int highest=1<<i;//将1左移i位,等价于2的i次方
            int len=sequence.size();
            for(int i=len-1;i>=0;i--)
            {
                sequence.push_back(highest+sequence[i]);
            }
        }
        return sequence;
    }
};




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值