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了。
2017-12-25 Updated
再稍微解释一下这个算法的具体道理:
n = 1 的时候,数组里是0 和 1, 也就是1的数目是0 1 (此为base case)
因为我们是从后往前向最左边“或”一个1。 所以当n = 2的时候,数组里1的数目是 0 1 2 1
n = 3时,数组里1的数目就是 0 1 2 1 2 3 2 1
n = 4时,数组里1的数目就是 0 1 2 1 2 3 2 1 2 3 4 3 2 3 2 1
如果说因为一路上都是向最左侧这么加一个一得到下一部分数组的。所以如果说f(n)是这个数列。那么f(n + 1)的新元素序列中的第一个,便和f(n)最后一个元素也差一个一,因为f(n + 1)的新元素序列是f(n)已有数列的逆向复制的同时最左端多加一个1,所以新元素序列里每一个相邻的元素都刚好差一个1。 这就是说为什么这是一个数学归纳法的原理
f(0) = {0}
f(1) = {0, 1}
有两个base case,然后任何f(n)和f(n + 1) (n > 1)就可以根据上面那条规则递归下去。
本文介绍了一种生成灰码序列的有效算法。通过使用ArrayList并基于数学归纳法原理,该算法能够在给定比特位数的情况下生成符合要求的灰码序列。
531

被折叠的 条评论
为什么被折叠?



