leetcode第89题:格雷编码
https://leetcode-cn.com/problems/gray-code/
【题目】
格雷编码是一个二进制数字系统,在该系统中,两个连续的数值仅有一个位数的差异。
给定一个代表编码总位数的非负整数 n,打印其格雷编码序列。即使有多个不同答案,你也只需要返回其中一种。
格雷编码序列必须以 0 开头。
示例 1:
输入: 2
输出: [0,1,3,2]
解释:
00 - 0
01 - 1
11 - 3
10 - 2
对于给定的 n,其格雷编码序列并不唯一。
例如,[0,2,3,1] 也是一个有效的格雷编码序列。
00 - 0
10 - 2
11 - 3
01 - 1
示例 2:
输入: 0
输出: [0]
解释: 我们定义格雷编码序列必须以 0 开头。
给定编码总位数为 n 的格雷编码序列,其长度为 2^n。当 n = 0 时,长度为 2^0 = 1。
因此,当 n = 0 时,其格雷编码序列为 [0]。
【思路】
我们考虑最常使用的格雷编码的形式,即示例1中的第一种形式。
对于二进制形式,如果有长度为i-1位的序列m,那么长度为i位的序列为:[m1, m2],其中m1为原始序列的元素在首位加'0',m2为原始序列的元素在首位加'1';
对于整数形式,m1为原始序列的元素,m2为原始序列的元素加上2^(i-1)。
【代码】
python版本
class Solution(object):
def grayCode(self, n):
"""
:type n: int
:rtype: List[int]
"""
if n == 0:
return [0]
ls = ['0', '1']
for i in range(1, n):
tmp1 = list(map(lambda x: '0' + x, copy.copy(ls)))
tmp2 = list(map(lambda x: '1' + x, copy.copy(ls[::-1])))
ls = tmp1 + tmp2
ls = list(map(lambda x: int(x, 2), ls))
return ls
C++版本
class Solution {
public:
vector<int> grayCode(int n) {
vector<int> res;
// 特殊情况
res.push_back(0);
if (n == 0)
return res;
res.push_back(1);
if (n == 1)
return res;
int add = 1;
for (int i = 1; i < n; i++) {
add *= 2;
for (int j = res.size() - 1; j >= 0; j--) {
res.push_back(res[j] + add);
}
}
return res;
}
};
前一篇文章:20T44-合并两个有序数组
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有