LeetCode-89 Gray Code

这篇博客介绍了如何利用递归规则生成格雷码序列。内容涉及格雷码的基本性质,转换方法以及如何通过Python代码实现从n位到(n+1)位的格雷码扩展。示例展示了对于给定的n值,如何生成符合要求的格雷码序列,并提供了具体的代码实现。

Description

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

Given an integer n representing the total number of bits in the code, return any sequence of gray code.

A gray code sequence must begin with 0.

Constraints:
• 1 <= n <= 16

Example

Example 1:
Input: n = 2
Output: [0,1,3,2]
Explanation:
00 - 0
01 - 1
11 - 3
10 - 2
[0,2,3,1] is also a valid gray code sequence.
00 - 0
10 - 2
11 - 3
01 - 1

Example 2:
Input: n = 1
Output: [0,1]

Submissions

经百度百科格雷码可知其转换方法:
基于格雷码是反射码的事实,利用递归的如下规则来构造:
• 1位格雷码有两个码字
• (n+1)位格雷码中的前2n个码字等于n位格雷码的码字,按顺序书写,加前缀0
• (n+1)位格雷码中的后2n个码字等于n位格雷码的码字,按逆序书写,加前缀1
• n+1位格雷码的集合 = n位格雷码集合(顺序)加前缀0 + n位格雷码集合(逆序)加前缀1
在这里插入图片描述
因此循环使第(n+1)位的格雷码序列等于 ‘0’+第n位的正序 加 ‘1’+第n位的逆序 即可,最后利用map函数将二进制数字列表转换为整型数组。

map() 会根据提供的函数对指定序列做映射。
第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。lambda表示匿名函数。

int() 函数用于将一个字符串或数字转换为整型。
class int(x, base=10),base表示进制数,默认十进制。

实现代码如下:

class Solution:
    def grayCode(self, n: int) -> List[int]:
        grays = dict()
        grays[0] = ['0']
        grays[1] = ['0', '1']
        for i in range(2, n + 1):
            res = []
            for pre in grays[i - 1]:
                res.append('0' + pre)
            for pre in grays[i - 1][::-1]:
                res.append('1' + pre)
            grays[i] = res
        return map(lambda x: int(x, 2), grays[n])     
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值