作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/gray-code/description/

题目描述

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位的格雷码序列。格雷码是指相邻的两个数字的二进制只会有一位不同。

解题方法

这个题目是属于回溯法的题目。但是,查了一下百度百科的格雷码,根本用不到回溯啊摔!!

下面是百度百科告诉的如何求n位的格雷码的方法。

递归生成码表

这种方法基于格雷码是反射码的事实,利用递归的如下规则来构造:

  1. 1位格雷码有两个码字
  2. (n+1)位格雷码中的前2n个码字等于n位格雷码的码字,按顺序书写,加前缀0
  3. (n+1)位格雷码中的后2n个码字等于n位格雷码的码字,按逆序书写,加前缀1
  4. n+1位格雷码的集合 = n位格雷码集合(顺序)加前缀0 + n位格雷码集合(逆序)加前缀1

简言之就是递归。第(n+1)位的格雷码序列=(‘0’+第n位的正序) + (‘1’+第n位的逆序)

题目中说了n是非负数,当n=0的时候,返回[0]即可。

所以循环版本:

class Solution(object):
def grayCode(self, n):
"""
:type n: int
:rtype: List[int]
"""
grays = dict()
grays[0] = ['0']
grays[1] = ['0', '1']
for i in range(2, n + 1):
n_gray = []
for pre in grays[i - 1]:
n_gray.append('0' + pre)
for pre in grays[i - 1][::-1]:
n_gray.append('1' + pre)
grays[i] = n_gray
return map(lambda x: int(x, 2), grays[n])

递归版本:

class Solution(object):
def grayCode(self, n):
"""
:type n: int
:rtype: List[int]
"""
return map(lambda x: int(x, 2), self.bit_gray(n)) def bit_gray(self, n):
ans = None
if n == 0:
ans = ['0']
elif n == 1:
ans = ['0', '1']
else:
pre_gray = self.bit_gray(n - 1)
ans = ['0' + x for x in pre_gray] + ['1' + x for x in pre_gray[::-1]]
return ans

C++代码如下:

class Solution {
public:
vector<int> grayCode(int n) {
if (n == 0) return {0};
if (n == 1) return {0, 1};
vector<int> res;
vector<int> pre = grayCode(n - 1);
for (int p : pre) {
res.push_back(p);
}
for (auto p = pre.rbegin(); p < pre.rend(); p++) {
res.push_back((1 << (n - 1)) + *p);
}
return res;
}
};

日期

2018 年 6 月 12 日 —— 实验室上午放假2333刷题吧
2018 年 12 月 20 日 —— 感冒害的我睡不着

【LeetCode】89. Gray Code 解题报告(Python & C++)的更多相关文章

  1. LeetCode: Gray Code 解题报告

    Gray CodeThe gray code is a binary numeral system where two successive values differ in only one bit ...

  2. leetCode 89.Gray Code (格雷码) 解题思路和方法

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

  3. [LeetCode] 89. Gray Code 格雷码

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

  4. Leetcode#89 Gray Code

    原题地址 二进制码 -> 格雷码:从最右边起,依次与左边相邻位异或,最左边一位不变.例如: 二进制: 1 0 0 1 1 1 0 |\|\|\|\|\|\| 格雷码: 1 1 0 1 0 0 1 ...

  5. 【LeetCode】120. Triangle 解题报告(Python)

    [LeetCode]120. Triangle 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址htt ...

  6. 89. Gray Code - LeetCode

    Question 89. Gray Code Solution 思路: n = 0 0 n = 1 0 1 n = 2 00 01 10 11 n = 3 000 001 010 011 100 10 ...

  7. LeetCode 1 Two Sum 解题报告

    LeetCode 1 Two Sum 解题报告 偶然间听见leetcode这个平台,这里面题量也不是很多200多题,打算平时有空在研究生期间就刷完,跟跟多的练习算法的人进行交流思想,一定的ACM算法积 ...

  8. 【LeetCode】Permutations II 解题报告

    [题目] Given a collection of numbers that might contain duplicates, return all possible unique permuta ...

  9. 【LeetCode】Island Perimeter 解题报告

    [LeetCode]Island Perimeter 解题报告 [LeetCode] https://leetcode.com/problems/island-perimeter/ Total Acc ...

随机推荐

  1. Excel-实现选择性粘贴(粘贴公式为文本)自动化,不想手动

    10.选择性粘贴(粘贴公式为文本)自动化,不想手动: (1)参考:https://jingyan.baidu.com/article/20b68a88a8bf55796cec62a3.html (2) ...

  2. 模拟串口UART的实现

    我所祷告的,就是要你们的爱心,在知识和见识上,多而又多,使你们能分辨是非,做诚实无过的人,直到基督的日子.--腓立比书[1:9~10] 最近在调的MCU的型号为STM32F030,配置芯片相较之前的M ...

  3. Hi3516开发笔记(六):通过HiTools使用USB/串口将uboot、kernel、roofts和userdata按照分区表烧写镜像

    若该文为原创文章,转载请注明原文出处本文章博客地址:https://hpzwl.blog.csdn.net/article/details/121706033红胖子(红模仿)的博文大全:开发技术集合( ...

  4. 【模板】无源汇有上下界可行流(网络流)/ZOJ2314

    先导知识 网络最大流 题目链接 https://vjudge.net/problem/ZOJ-2314 题目大意 多组数据,第一行为数据组数 \(T\). 对于每一组数据,第一行为 \(n,m\) 表 ...

  5. django中的filter(), all(), get()

    1. 类名.objects中的get(), filter(), all() 的区别 结论: (1)all()返回的是QuerySet对象,程序并没有真的在数据库中执行SQL语句查询数据,但支持迭代,使 ...

  6. C++构造函数和析构函数初步认识

    构造函数 1.构造函数与类名相同,是特殊的公有成员函数.2.构造函数无函数返回类型说明,实际上构造函数是有返回值的,其返回值类型即为构造函数所构建到的对象.3.当新对象被建立时,构造函数便被自动调用, ...

  7. Java面试基础--(出现次数最多的字符串)

    题目:给定字符串,求出现次数最多的那个字母及次数,如有多个 重复则都输出. eg,String data ="aaavzadfsdfsdhshdWashfasdf": 思路: 1. ...

  8. Tomcat(2):配置Tomcat

    1,打开IDEA创建一个项目 2,配置Tomcat服务器 3,运行 5,成功 t t

  9. 【C/C++】BanGDream活动点数计算器

    作为一个白嫖咸鱼,我每个活动都只打出三星卡就不玩了,于是写了一个模拟器,算算还要打几把hhh #include <iostream> #include <algorithm> ...

  10. 避免警报疲劳:每个 K8s 工程团队的 8 个技巧

    避免警报疲劳:每个 K8s 工程团队的 8 个技巧 监控 Kubernetes 集群并不容易,警报疲劳通常是一个问题.阅读这篇文章,了解减少警报疲劳的有用提示. 如果您是随叫随到团队的一员,您可能知道 ...