博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[leetcode] 89. Gray Code 解题报告
阅读量:3675 次
发布时间:2019-05-21

本文共 1382 字,大约阅读时间需要 4 分钟。

题目链接:https://leetcode.com/problems/gray-code/

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 - 001 - 111 - 310 - 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.

思路:利用模拟法来产生格雷码的时候有一个,即当所有三位的格雷码可以由所有二位格雷码+将二位所有格雷码从从最后一个到第一个依次最左边加1构成.例如二位的格雷码依次是00, 01, 11, 10.而三位的格雷码就是继承二位的格雷码+逆序二位格雷码并在左边加1:110, 111, 101, 100.这样我们就可以得到所有的3位格雷为00, 01, 11, 10, 110, 111, 101, 100.

代码如下:

class Solution {public:    vector
grayCode(int n) { vector
result(1, 0); for(int i = 0; i < n; i++) { int high = 1<
=0; j--) result.push_back(high+result[j]); } return result; }};

而实际上还有一种数学的方法来解决,不过并不是很推荐,因为面试不是考察你的数学,而是编程思维.

class Solution {public:    vector
grayCode(int n) { int len = 1 << n; vector
result; for(int i = 0; i < len; i++) result.push_back(i ^ (i>>1)); return result; }};
参考:http://fisherlei.blogspot.com/2012/12/leetcode-gray-code.html

你可能感兴趣的文章
爬虫介绍
查看>>
爬虫入门bs4之多线程
查看>>
动态网页抓取一
查看>>
动态网页抓取二下载MP3
查看>>
bs4爬取笔趣阁小说
查看>>
xctf 攻防世界 crypto
查看>>
selenium驱动安装配置
查看>>
selenium模拟登录淘宝
查看>>
selenium爬取京东商品信息
查看>>
fiddler抓包分析豆瓣250
查看>>
selenium踩坑集
查看>>
requests使用代理ip访问网站
查看>>
selenium使用代理ip访问网站
查看>>
基于GIS的国土空间规划平台建设
查看>>
基于WebGis的智慧园区数字孪生平台
查看>>
基于BIM+GIS的管控平台
查看>>
基于SuperMap10i 开发的全过程咨询管理平台的研究
查看>>
应急指挥中心系统的研究与设计
查看>>
基于BIM+GIS钢结构全生命周期管理平台项目
查看>>
轨道交通GIS平台的应用分析
查看>>