博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode 89 Gray Code
阅读量:4170 次
发布时间:2019-05-26

本文共 1774 字,大约阅读时间需要 5 分钟。

题目描述:
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<
C++代码:

class Solution {public:    vector
grayCode(int n) { vector
sequence; sequence.push_back(0); for(int i=0;i
=0;i--) { sequence.push_back(highest+sequence[i]); } } return sequence; }};

你可能感兴趣的文章
jsp中上传文件的源代码
查看>>
使用SQL语句查询表中重复记录并删除
查看>>
将xml中的数据导入到数据库
查看>>
Qt容器测试
查看>>
自定义插件
查看>>
编译数据库ODBC
查看>>
无法解析的外部符号的 3 种可能
查看>>
webalizer流量分析软件windows下的配置与使用
查看>>
Java的数组(Array)、Vector、ArrayList、HashMap的异同
查看>>
Apache的使用方法
查看>>
PHP环境配置:Apach+Tomcat+mysql+php
查看>>
深入理解Glibc堆的实现(上)
查看>>
C&C远控工具:Ares
查看>>
窃密团伙瞄准企业机密信息,备用病毒超60个
查看>>
勒索软件的“中流砥柱”:深入分析GandCrab新型Evasive感染链
查看>>
FIN7 2.0归来:“借尸还魂”的可疑组织们
查看>>
CVE-2019-5018:Sqlite3 远程代码执行漏洞
查看>>
HITB | 360议题分享:卫星可欺骗 地震警报可伪造
查看>>
公有云容器安全
查看>>
为逃避检测而取消持久性:KPOT v2.0信息窃取恶意软件分析
查看>>