作者: 负雪明烛
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. IDEA中对代码进行测试

    一. 建立对应得目录 二.导入junit依赖 <dependency> <groupId>junit</groupId> <artifactId>jun ...

  2. k8s-hpa自动横向扩容

    目录 hpa自动扩容 官方文档 HPA是什么 Horizontal Pod Autoscaler 演练 参数 案例:监控cpu,内存,每秒数据包自动扩容 度量指标 pod清单案例-pod定义cup内存 ...

  3. 强化学习实战 | 表格型Q-Learning玩井字棋(二)

    在 强化学习实战 | 表格型Q-Learning玩井字棋(一)中,我们构建了以Game() 和 Agent() 类为基础的框架,本篇我们要让agent不断对弈,维护Q表格,提升棋力.那么我们先来盘算一 ...

  4. css通配样式初始化(多款,供君自选)

    腾讯官网 body,ol,ul,h1,h2,h3,h4,h5,h6,p,th,td,dl,dd,form,fieldset,legend,input,textarea,select{margin:0; ...

  5. [学习总结]8、android 自定义控件 使用declare-styleable进行配置属性(源码角度)

    declare-styleable:declare-styleable是给自定义控件添加自定义属性用的. 官方的相关内部控件的配置属性文档:http://developer.android.com/r ...

  6. 监测linux系统负载与CPU、内存、硬盘、用户数的shell脚本

    本节主要内容: 利用Shell脚本来监控Linux系统的负载.CPU.内存.硬盘.用户登录数. 一.linux系统告警邮件脚本 # vim /scripts/sys-warning.sh #!/bin ...

  7. Javascript 数组对象常用的API

    常用的JS数组对象API ES5及以前的Api ECMAScript5为数组定义了5个迭代方法,每个方法接收两个参数, 一个是每项运行的函数,一个是运行该函数的作用域对象(可选项),传入这些方法的函数 ...

  8. 使用cookie记录用户上次访问网页的时间,并返回到页面

    package com.hopetesting.cookie;import javax.servlet.ServletException;import javax.servlet.annotation ...

  9. 注册页面css版本

    <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" ...

  10. 【JAVA今法修真】 第四章 redis特性 击穿雪崩!

    感谢这段时间大家的支持,关注我的微信号:南橘ryc ,回复云小霄,就可以获取到最新的福利靓照一张,还等什么,赶快来加入我们吧~ "明日便是决赛了,咋只会用法器没练过法术呢.". 选 ...