Gray Code 解答
2015-10-18 09:07
302 查看
Question
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.
For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that.
Solution
Key to the solution is to find that we can get grey code of n by grey code of (n - 1).A simple illustration of from 2 to 3
When input is n, grey code size is 2n.
1. For first 2n - 1, we just get from grey code of (n - 1)
2. For second 2n - 1, we traverse grey code of (n - 1) in back order, and add 1 to head for each element.
public class Solution { public List<Integer> grayCode(int n) { if (n == 0) { List<Integer> result = new ArrayList<Integer>(); result.add(0); return result; } List<Integer> result = grayCode(n - 1); int length = result.size(); int addNumber = 1 << (n - 1); for (int i = length - 1; i >= 0; i--) { int tmp = result.get(i); result.add(addNumber + tmp); } return result; } }
相关文章推荐
- 使用函数实现两个数的交换。
- 开源媒体播放器 MPlayer 1.2 发布
- poj1323-Game Prediction(贪心思想)
- NFS 服务配置
- ARP欺骗的实现
- 造成win2008 500内部错误不能显示详细错误的原因和解决方法
- 实现一个函数,打印乘法口诀表,口诀表的行数和列数自己指定,输入多少打印几乘几的乘法表
- TCP和UDP之间的区别
- Java 类反射机制分析
- 复习网络体系结构与网络协议
- 终于看到golang的深入解读了
- ASI和AFN有什么区别
- C语言基础知识
- Qt5布局管理项目示例
- Qt模板库、工具即控件项目示例
- 线程相关知识
- Socket规划(1)
- C++ Primer章课后编程问题
- ViewPager.getChildCount() 含义
- 老王学linux-更改语言