【LeetCode】89. Gray Code 解题报告(Python & C++)
作者: 负雪明烛
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位格雷码有两个码字
- (n+1)位格雷码中的前2n个码字等于n位格雷码的码字,按顺序书写,加前缀0
- (n+1)位格雷码中的后2n个码字等于n位格雷码的码字,按逆序书写,加前缀1
- 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++)的更多相关文章
- LeetCode: Gray Code 解题报告
Gray CodeThe gray code is a binary numeral system where two successive values differ in only one bit ...
- leetCode 89.Gray Code (格雷码) 解题思路和方法
The gray code is a binary numeral system where two successive values differ in only one bit. Given a ...
- [LeetCode] 89. Gray Code 格雷码
The gray code is a binary numeral system where two successive values differ in only one bit. Given a ...
- Leetcode#89 Gray Code
原题地址 二进制码 -> 格雷码:从最右边起,依次与左边相邻位异或,最左边一位不变.例如: 二进制: 1 0 0 1 1 1 0 |\|\|\|\|\|\| 格雷码: 1 1 0 1 0 0 1 ...
- 【LeetCode】120. Triangle 解题报告(Python)
[LeetCode]120. Triangle 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址htt ...
- 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 ...
- LeetCode 1 Two Sum 解题报告
LeetCode 1 Two Sum 解题报告 偶然间听见leetcode这个平台,这里面题量也不是很多200多题,打算平时有空在研究生期间就刷完,跟跟多的练习算法的人进行交流思想,一定的ACM算法积 ...
- 【LeetCode】Permutations II 解题报告
[题目] Given a collection of numbers that might contain duplicates, return all possible unique permuta ...
- 【LeetCode】Island Perimeter 解题报告
[LeetCode]Island Perimeter 解题报告 [LeetCode] https://leetcode.com/problems/island-perimeter/ Total Acc ...
随机推荐
- 44-Count and Say
Count and Say My Submissions QuestionEditorial Solution Total Accepted: 79863 Total Submissions: 275 ...
- Redis集合解决大数据筛选
Redis集合:集合是什么,就是一堆确定的数据放在一起,数学上集合有交集.并集的概念,这个就可以用来做大数据的筛选功能. 以商品为例,假如商品有颜色和分类.价格区间等属性. 给所有统一颜色的商品放一个 ...
- 内存管理malloc 2
malloc可以在函数指针内使用.#include <stdio.h> #include <stdlib.h> char * get_string() { //char s[] ...
- 宏GENERATED_BODY做了什么?
Version:4.26.2 UE4 C++工程名:MyProject \ 一般语境下,我们说c++源码的编译大体分为:预处理.编译.链接; cppreference-translation_phas ...
- 学习java 7.27
学习内容: 创建树 Swing 使用JTree对象来代表一棵树,JTree树中结点可以使用TreePath来标识,该对象封装了当前结点及其所有的父结点. 当一个结点具有子结点时,该结点有两种状态: 展 ...
- 自然语言式parsing
got NUM(1) Is NUM(1) an expr? Is NUM(1) a term? Is NUM(1) a number? is_term got -(-) -(-) was back i ...
- Kafka(一)【概述、入门、架构原理】
目录 一.Kafka概述 1.1 定义 二.Kafka快速入门 2.1 安装部署 2.2 配置文件解析 2.3Kafka群起脚本 2.4 topic(增删改查) 2.5 生产和消费者命令行操作 三.K ...
- Java Swing布局管理器GridBagLayout的使用示例 [转]
GridBagLayout是java里面最重要的布局管理器之一,可以做出很复杂的布局,可以说GridBagLayout是必须要学好的的, GridBagLayout 类是一个灵活的布局管理器,它不要求 ...
- 【编程思想】【设计模式】【创建模式creational】建造者模式builder
Python版 https://github.com/faif/python-patterns/blob/master/creational/builder.py #!/usr/bin/python ...
- 【Linux】【Service】【OpenSSL】原理及实现
1. 概念 1.1. SSL(Secure Sockets Layer安全层套接字)/TLS(Transport Layer Security传输层套接字). 最常见的应用是在网站安全方面,用于htt ...