LeetCode Gray Code
2015-10-25 08:43
381 查看
原题链接在这里: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
题解:
根据graycode的特性:在n增大1时,在原有list的末尾按照原有list的倒序每个数字首位digit加上一个1 加回到list中.
n = 0时,[0]
n = 1时,[0,1]
n = 2时,[00,01,11,10] 原有[0,1], 按照倒序[1,0], 首位加1变成[11,10]加回到原有的[0,1]后面, 就变成[0, 1, 11, 10]了.
n = 3时,[000,001,011,010,110,111,101,100]
Time Complexity: O(2^n). Space: O(1).不考虑res.
AC Java:
题目:
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
题解:
根据graycode的特性:在n增大1时,在原有list的末尾按照原有list的倒序每个数字首位digit加上一个1 加回到list中.
n = 0时,[0]
n = 1时,[0,1]
n = 2时,[00,01,11,10] 原有[0,1], 按照倒序[1,0], 首位加1变成[11,10]加回到原有的[0,1]后面, 就变成[0, 1, 11, 10]了.
n = 3时,[000,001,011,010,110,111,101,100]
Time Complexity: O(2^n). Space: O(1).不考虑res.
AC Java:
public class Solution { public List<Integer> grayCode(int n) { List<Integer> res = new ArrayList<Integer>(); if(n<0){ return res; } //when n = 0, return [0] res.add(0); for(int i = 0; i<n; i++){ int len = res.size(); //addNum 是要加的首位1 int addNum = 1<<i; for(int j = len-1; j>=0; j--){ res.add(addNum+res.get(j)); } } return res; } }
相关文章推荐
- MyReport报表系统
- iOS 【真机调试-免证书-开发者信任问题】
- 编程资源:看雪大礼包2010
- 【SSH项目实战】国税协同平台-7.POI导入用户列表文件
- 【软件工程】软工视频(三)软件需求分析
- 编程开发之make
- 重写PHP的explode办法
- 浏览器没有声音
- 【C#】.NET的相关概念
- 编程开发之GCC
- mysql5.5
- Single Number III - LeetCode
- 【Flume NG用户指南】(2)构造
- Java 笔试:算法笔记
- iOS常用小功能集锦
- Java 笔试:数据结构笔记
- django 两种创建模型实例的方法
- django 两种创建模型实例的方法
- [学习]用tarjian算法求强连通分量,tarjian算法缩点[学习知识~]
- pbfunc外部函数扩展应用-在Powerbuilder中进行Http的GET、POST操作