LeetCode 89. Gray Code(生成格雷码)
2016-05-01 17:10
507 查看
public class Solution { public List<Integer> grayCode(int n) { int all = 1<<n; List<Integer> result = new ArrayList<Integer>(all);//预分配空间 result.add(0); if(n==0)return result; result.add(1); if(n==1)return result ; int count = 2; int index = 1; int base = 2; while(count<all){ if(index<0){ index = count-1; base = base << 1; } result.add(base+result.get(index)); count++; index--; } return result; } }
基本思路很简单:
假设有格雷码:a[0]=0,a[1]=1;接下来就是
a[2]=1a[1];a[3]=1a[0];(字符串拼接,不是乘法)
即把下一个最高位置为1,将目前有的格雷码倒序输出,加上最高位的1
这样使用O(n)的时间就能生成所有格雷码
相关文章推荐
- HTML学习笔记——标签<canvas>
- IO学习(八)纯文本的拷贝
- Android 高清加载巨图方案 拒绝压缩图片
- ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)
- JAVA多线程之中断机制(如何处理中断?)
- 0501-构建之法6,7章读后感
- 如何用malloc创建二维数组
- 康拓展开
- 图标字体 VS 雪碧图——图标字体应用实践
- android之wifi开发(一)
- TreeMap、HashMap、ConcurrentSkipListMap之性能比较
- Linux下 nginx + php 环境搭建
- MySQL 下 ROW_NUMBER / DENSE_RANK / RANK 的实现
- 我的第一个Retrofit小demo
- 持续交付之六——构建与部署的脚本化
- poj 1002 487-3279
- ERROR! The server quit without updating PID file (/var/lib/mysql/service.pid).
- 梦断代码阅读笔记01
- 《Java程序设计》第9周学习总结
- [解决]UserLibrary中的jar包不会自动发布Tomcat的lib目录下(基于MyEclipse2014)