Gray Code
来源:互联网 发布:grub安装ubuntu 编辑:程序博客网 时间:2024/06/05 19:03
https://oj.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 [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.
public List<Integer> grayCode(int n)
这一题算是一个有固定解法的题。很难玩出别的什么花样。
先说算法。首先推荐解集为ArrayList,这样子复杂度会降低一个指数级别。解集先push一个0进去。
然后做n次循环。每次循环里面基于当前List的size做一个从尾到头的循环。
把取出来的元素或一个1 << i - 1再放回去。如此...就可以了。
先放代码吧:
public List<Integer> grayCode(int n) { List<Integer> res = new ArrayList<Integer>(); res.add(0); if(n < 1) return res; res.add(1); for(int i = 1; i < n; i++){ int cur_size = res.size() - 1; while(cur_size >= 0){ res.add(res.get(cur_size) | 1 << i); cur_size--; } } return res; }
原理其实不是很难理解。其实就是基于这么一个类似数学归纳法的原理:
1. 0 和 1 之间就差一位吧。
2. 那么假设数组里面的都是Gray code。 那么两两之间就差一个bit对吧?那么如果我在最后那一位上面再加一个1 << i - 1, 那么就和最后一个数就差一个bit对吧?那么我就这么倒着遍历放,其实也就是利用每一层形成的答案子集里每一个数值相差一个bit的现成效果。最后整个答案都是gray code了。
- Gray Code
- Gray Code
- gray code
- Gray Code
- Gray Code
- Gray Code
- Gray Code
- Gray Code
- Gray Code
- Gray Code
- Gray Code
- Gray Code
- Gray Code
- Gray Code
- Gray Code
- Gray Code
- Gray Code
- Gray Code
- Leetcode NO.59 Spiral Matrix II
- 学习计算机图形学OpenGL绘图
- Leetcode NO.27 Remove Element
- 一款好用的文件比较工具Meld
- Merge Sorted Array
- Gray Code
- mysql table is read only 解决
- Selenium
- CSDN我的收藏夹链接
- OGC
- [BZOJ 3680]吊打XXX(广义费马点、模拟退火搜索)
- 内核编译选项20要20不要
- Your content must have a ListView whose id attribute is 'android.R.id.list'
- LeetCode(1) Two Sum实现