89. Gray Code
2016-05-23 09:16
357 查看
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
code sequence is:
Note:
For a given n, a gray code sequence is not uniquely defined.
For example,
above definition.
For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that.
题意:长度为n的格雷码的构造。
思路:长度为2的格雷码有4个:00,01,11,10, (即:0,1,3,2);则存在这样的关系,长度为3的格雷码有8个,前4个是 0-00, 0-01, 0-11, 0-10,(即:0,1,3,2), 后四个是:1-00,1-01,1-11,1-10。就是在前一个长度的格雷码表示上前半段加上0(表示的数值不变),后半段加上1即可。对于从长度n-1到长度到n的变化过程也符合这个规律。
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的格雷码的构造。
思路:长度为2的格雷码有4个:00,01,11,10, (即:0,1,3,2);则存在这样的关系,长度为3的格雷码有8个,前4个是 0-00, 0-01, 0-11, 0-10,(即:0,1,3,2), 后四个是:1-00,1-01,1-11,1-10。就是在前一个长度的格雷码表示上前半段加上0(表示的数值不变),后半段加上1即可。对于从长度n-1到长度到n的变化过程也符合这个规律。
class Solution { public: vector<int> grayCode(int n) { vector<int> res(1<<n, 0); int count = 1; for (int i = 1; i <= n; i++){ int count = 0; for (int j = (1<<i)-1; j > (1<<i-1)-1; j--){ res[j] = res[count++] | 1 << i-1; } } return res; } };
相关文章推荐
- WPF 之 左键弹出操作菜单,并禁用右键菜单
- 提交 git 项目 到 github 在 centos 7
- Ibatis中的#和$
- java设计模式-单例模式
- python正则表达式
- 编码简析
- myeclipse快捷键
- yii2分页的基本使用及其配置详解
- SQL Server 移动系统数据库
- 解决Visual Studio 2012 Update 4 RC启动调试失败的方案
- javascript-表格移动光标变色
- 打印java文件中的所有注释
- 每天一个Linux命令(25)chgrp命令
- Could not find the Visual SourceSafe Internet Web Service connection information for the specified database Would you like to launch the Visual sourceSafe connection wizard?
- HTMl5的sessionStorage和localStorage
- javascript-下拉菜单的实现
- 解决网站播放视频不要广告
- java 中List.subList 总结
- 拿走不谢!22 个 Android Studio 优秀插件汇总
- Docker1.10.1以上版本配置http API访问