leetcode 89. Gray Code
来源:互联网 发布:个人域名注册方法 编辑:程序博客网 时间:2024/06/07 07:50
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.
这道题可以递归来得到:比如,n=3时的gray code可以基于n=2的情形来获得。
00,01,11,10 -> (000,001,011,010 ) (110,111,101,100)。 前半部分 是由n=2的情形加上前缀0所得,后半部分 是由n=2的情形倒过来遍历加上前缀1所得。下面更直观地展示出来了:
n = 1
0
1
n=2
0 0
0 1
1 1
1 0
n=3
0 0 0
0 0 1
0 1 1
0 1 0
1 1 0
1 1 1
1 0 1
1 0 0
public List<Integer> grayCode(int n) {List<Integer> result=new ArrayList<Integer>();if(n==0){result.add(0);return result;}List<Integer> tmpList=grayCode(n-1);//加上前缀0,数字保持不变result.addAll(tmpList);//加上前缀1,用“或”操作来加上前缀1int mask=(1 << n-1);for(int i=tmpList.size()-1;i>=0;i--){int theNum=tmpList.get(i);result.add(theNum | mask);}return result;}当然了,大神也按照这个思路给出了迭代的解法。
1:i=0,结果是0,1
2:i=1,加前缀1*
3:i=2,加前缀1**
而每次加前缀,数量都必定多一倍。
public List<Integer> grayCode(int n) { List<Integer> rs=new ArrayList<Integer>(); rs.add(0); for(int i=0;i<n;i++){ int size=rs.size(); for(int k=size-1;k>=0;k--) rs.add(rs.get(k) | 1<<i); } return rs;}除了这个思路之外,大神还有其他高大上的思路。运用了数字集成电路设计的标准解法:digital IC design binary to grey convert。https://www.electrical4u.com/binary-to-gray-code-converter-and-grey-to-binary-code-converter/ (什么鬼啦其实我根本看不懂啦。)
发现了一个简单的公式:G(i) = i^ (i/2).
public List<Integer> grayCode(int n) { int count = (int)Math.pow(2,n); List<Integer> res = new ArrayList<>(); for(int i = 0; i < count; i++){ res.add( i ^ (i>>1) ); } return res;}
说到异或的性质,我只能想到:
1^1=0,0^1=1,所以某一位与1异或,一定会置反
1^0=1,0^0=0,所以某一位与0异或,一定会不变
所以这个解法跟这个性质有没有关系呢?...我也不知道啊。但是这个解法真的好神奇呀!
- [LeetCode]89.Gray Code
- LeetCode 89. Gray Code
- [Leetcode] 89. Gray Code
- LeetCode --- 89. Gray Code
- [leetcode] 89.Gray Code
- 89. Gray Code LeetCode
- [LeetCode]89. Gray Code
- Leetcode 89. Gray Code
- [leetcode] 89. Gray Code
- LeetCode *** 89. Gray Code
- [LeetCode]89. Gray Code
- leetcode 89. Gray Code
- leetcode 89. Gray Code
- [leetcode]89. Gray Code
- LeetCode-89.Gray Code
- LeetCode 89. Gray Code
- LeetCode - 89. Gray Code
- [LeetCode] 89. Gray Code
- ruby 懒加载 lazy
- 使用devstack快速安装、部署openstack
- 对于Spring Cloud Feign入门示例的一点思考
- Kanade's sum HDU
- 在有TableView的页面一行代码收起键盘
- leetcode 89. Gray Code
- iOS性能优化
- POJ 2195 Going Home (费用流)
- openoffice + jodconverter 接收 修订 和 跟踪,得到最终版本
- 在IDEA中实战Git
- 使用Keil进行在线调试
- zookeeper单机单独实例安装-windows
- Elasticsearch 注册为Windows服务
- 【数据结构】【堆排序】