Gray Code
来源:互联网 发布:免费漫画软件哪个好 编辑:程序博客网 时间:2024/06/06 10:45
题目名称
Gray Code—LeetCode链接
描述
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.
For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that.
分析
n=1时:graycode=[0,1],二进制表示为[0,1];
n=2时:graycode=[0,1,3,2],二进制表示为[00,01,11,10];注意这里并不是0,1,2,3;
n=3时:graycode=[0,1,3,2,6,7,5,4],前四个数与n=2时完全相同,在分析二进制表示:
n=2十进制:0, 1, 3, 2二进制:00,01,11,10n=3十进制:0, 1, 3, 2, 6, 7, 5, 4二进制:000,001,011,010,110,111,101,100000,001,011,010100,101,111,1106比2多4,7比3多4,5比1多4,4比0多4
由此得到一个递推公式,n+1中的元素可以这样得到:
n+1中的graycode码个数是n中的两倍,首先复制一份n中的元素,然后按照n中的元素从后往前依次增加2的n次方,加入到n+1中。
这样保证了相邻元素之间只有一个位的数字不同。
C++代码
vector<int> grayCode(int n) { vector<int> res; if(n<0) return res; if(n==0){ res.push_back(0); return res; } res.push_back(0); res.push_back(1); for(int i=1;i<n;i++){ vector<int> temp(res); //这里是计算2的i次方,将1向坐位移i个单位 int add = 1<<i; int a=0,b=temp.size()-1; for(b;b>=a;b--){ temp.push_back(temp[b]+add); } res = temp; } return res;}
总结
采用迭代法。
- Gray Code
- Gray Code
- gray code
- Gray Code
- Gray Code
- Gray Code
- Gray Code
- Gray Code
- Gray Code
- Gray Code
- Gray Code
- Gray Code
- Gray Code
- Gray Code
- Gray Code
- Gray Code
- Gray Code
- Gray Code
- ActiveMQ学习笔记(6)——JMS消息类型
- Zxing 实现二维码的生成方法
- HDU 2602 Bone Collector
- 使我的报表从第二页开始打印。(2015-10-27)
- 简单齐全的ExtendListVeiw 去掉系统箭头,二级菜单删除等功能
- Gray Code
- OpenDaylight集群功能验证性实验二_可靠性验证
- 关于65535方法数(不删代码,不做插件化,square的成果)
- 设计模式之Bridge(桥梁)模式
- 032.NSValue NSNumber 包装类
- Android图片旋转,缩放,位移,倾斜,对称完整示例(一)——imageView.setImageMatrix(matrix)和Matrix
- ListView或GridView 顶部间距
- springmvc +uploadify 3.2.1 上传文件
- Git 菜鸟变大神 (一) 本地仓库的创建和初始化