生成格雷码(Gray Code)
来源:互联网 发布:xbox one国行解锁 知乎 编辑:程序博客网 时间:2024/06/07 18:27
题目原型:
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时,格雷码为{“0”},{“1”},当n=2时,格雷码为{“00”,“01”},{“11”,“10”},当n=3时,格雷码为{“000”,“001”,“011”,“010”},{“110”,“111”,“101”,“100”}。。。看到这里我们是否发现了一个规律,就
是n位的格雷码是在n-1的基础上,先从前往后扫描,在最前面插入一个“0”,然后从后往前扫描,插入一个“1”.
以此类推,便可得到结果。
public ArrayList<Integer> grayCode(int n) {ArrayList<Integer> answer = new ArrayList<Integer>();if(n==0){answer.add(0);return answer;}ArrayList<String> result = generateCode(n);for(String str : result){answer.add(transfer(str));}return answer; }//二进制转十进制public int transfer(String binary){int result = 0;for(int i = binary.length()-1;i>=0;i--){result+=(binary.charAt(i)-'0')*(int)Math.pow(2, binary.length()-i-1);}return result;}public ArrayList<String> generateCode(int n){ArrayList<String> tmp = new ArrayList<String>();ArrayList<String> result = new ArrayList<String>();tmp.add("0");tmp.add("1");if(n==1){return tmp;}for(int i = 2;i<=n;i++){result = new ArrayList<String>();for(String str : tmp){result.add("0"+str);}for(int j = tmp.size()-1;j>=0;j--){result.add("1"+tmp.get(j));}tmp = result;}return result;}
- 生成格雷码(Gray Code)
- LeetCode 89. Gray Code(生成格雷码)
- 格雷码(Gray Code)的生成
- 格雷码(Gray Code)
- 递归——生成格雷码(gray code)
- LeetCode | Gray Code(格雷码)
- Gray Code 简介及生成
- 递归生成格雷码 gray code generation using recursion(c++)
- Gray Code (格雷码编码) 【leetcode】
- LeetCode OJ 之 Gray Code(格雷码)
- [C++]LeetCode: 86 Gray Code (格雷码)
- Algorithm Gossip: 格雷码(Gray Code)
- c++实现gray code(格雷码)
- LeetCode 89. Gray Code(格雷码)
- LeetCode#89. Gray Code(格雷码)
- [LeetCode] 格雷码(Gray Code)
- Gray Code 格雷码 @LeetCode
- Gray Code 格雷码编码
- 业余开发的wpf 客户端终于完工了。。晒晒截图
- java对HashMap中的key或者value值进行排序!
- javascript数组元素的添加、删除与插入以及参数数组的使用
- 树型选择排序
- Objective-C 异步任务
- 生成格雷码(Gray Code)
- 关于错误 at::0 can't find referenced pointcut *****
- vector模板类的用法
- codeForces 373B
- CAM350软件使用说明----PADS相关
- IOS页面之间通过委托(协议)传值
- HEVC参考代码HM10.0的使用
- 什么是矩阵的范数
- JS跨域及Ajax实现