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了。

0 0