[leetcode] 89. Gray Code 解题报告
2015-12-07 15:10
405 查看
题目链接: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
is:
Note:
For a given n, a gray code sequence is not uniquely defined.
For example,
思路:利用模拟法来产生格雷码的时候有一个镜面定理,即当所有三位的格雷码可以由所有二位格雷码+将二位所有格雷码从从最后一个到第一个依次最左边加1构成.例如二位的格雷码依次是00, 01, 11, 10.而三位的格雷码就是继承二位的格雷码+逆序二位格雷码并在左边加1:110, 111, 101, 100.这样我们就可以得到所有的3位格雷为00,
01, 11, 10, 110, 111, 101, 100.
代码如下:
而实际上还有一种数学的方法来解决,不过并不是很推荐,因为面试不是考察你的数学,而是编程思维.
参考:http://fisherlei.blogspot.com/2012/12/leetcode-gray-code.html
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 - 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.
思路:利用模拟法来产生格雷码的时候有一个镜面定理,即当所有三位的格雷码可以由所有二位格雷码+将二位所有格雷码从从最后一个到第一个依次最左边加1构成.例如二位的格雷码依次是00, 01, 11, 10.而三位的格雷码就是继承二位的格雷码+逆序二位格雷码并在左边加1:110, 111, 101, 100.这样我们就可以得到所有的3位格雷为00,
01, 11, 10, 110, 111, 101, 100.
代码如下:
class Solution { public: vector<int> grayCode(int n) { vector<int> result(1, 0); for(int i = 0; i < n; i++) { int high = 1<<i, len = result.size(); for(int j = len-1; j >=0; j--) result.push_back(high+result[j]); } return result; } };
而实际上还有一种数学的方法来解决,不过并不是很推荐,因为面试不是考察你的数学,而是编程思维.
class Solution { public: vector<int> grayCode(int n) { int len = 1 << n; vector<int> 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
相关文章推荐
- LeetCode() Super Ugly Number
- 6-对象流(对象的序列化)
- Debian下搭建Nginx和Tomcat服务器实现负载均衡的方案
- Android popupwindow 弹出的位置问题
- mybatis在xml文件中处理大于号小于号的方法
- Leetcode题解(七)
- Hadoop 2.7.1 集群模式安装【二】环境配置
- Deformity ASP/ASPX Webshell、Webshell Hidden Learning
- 冒泡 代码范例
- 5-数据流
- 数据存储之文件存储
- Windows上部署Redis-植入Windows服务
- 4-标准输入输出流(转换流)
- 关于启用 HTTPS 的一些经验分享
- codeigniter2.2.5连接mssql2008Rc2
- Java Remote Debug
- 集群?
- SpringMVC存取Session的两种方法
- #pragram once 和 #ifndef 辨别
- 3(1)-字符缓冲流