【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 ...
随机推荐
- C++你不知道的事
class A { public: A() { cout<<"A's constructor"<<endl; } virtual ~A() { cout&l ...
- 前端2 — CSS — 更新完毕
1.CSS是什么? 指:Cascading Style Sheet --- 层叠样式表 CSS 即:美化网页( 在HTML不是说过W3C规定网页为三种标准嘛,结构层HTML已经玩了,而这个CSS就是 ...
- 【二分答案】CF1613 C. Poisoned Dagger
题目:Problem - C - Codeforces 本题的优解是二分答案,但我其实不会二分,本质是用了两个指针作为边界,然后不断对半缩小范围来快速确定答案. 神奇的二分法 代码: #include ...
- myatoi
atoi (表示 ascii to integer)是把字符串转换成整型数的一个函数,应用在计算机程序和办公软件中.int atoi(const char *nptr) 函数会扫描参数 nptr字符串 ...
- deque、queue和stack深度探索(上)
deque是可双端扩展的双端队列,蓝色部分就是它的迭代器类,拥有四个指针,第一个cur用来指向当前元素,first指向当前buffer头部,last指向当前buffer尾部,node指向map自己当前 ...
- Advanced C++ | Virtual Constructor
Can we make a class constructor virtual in C++ to create polymorphic objects? No. C++ being static t ...
- vue-cli4脚手架搭建一
涉及内容 html css javascript node.js npm webpack 2.9.6是常用版本 vue-cli4是基于webpack的 webpack是基于node ...
- SpringAOP浅析
1.问题 问题:想要添加日志记录.性能监控.安全监测 2.最初解决方案 2.1.最初解决方案 缺点:太多重复代码,且紧耦合 2.2.抽象类进行共性设计,子类进行个性设计,此处不讲解,缺点一荣俱荣,一损 ...
- [BUUCTF]REVERSE——Java逆向解密
Java逆向解密 附件 步骤: 根据题目提示是java语言编写的程序,用jd-gui反编译一下 百度了一些java里的函数后读懂了这段程序的意思,将我们输入的字符串依次+'@',然后跟32异或,得到K ...
- ASP.NET WebApi 依赖 SAP Connector dll 报错
说明 本地 VS 开发 ASP.NET WebApi 调试运行没有问题,但发布到服务器 IIS 上就报错.结果发现是 SAP 依赖库的问题:sapnco.dll.sapnco_utils.dll. 错 ...