89Gray Code

来源:互联网 发布:java request 编辑:程序博客网 时间:2024/06/18 12:30

题目链接: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 [0,1,3,2]. Its gray code sequence is:00 - 001 - 111 - 310 - 2Note: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.

解题思路:
这题的考点是格雷码的编码规则,以及位操作
一开始自己只是就题论题,并没有考虑到格雷码。
思路是:
1. 对每一个二进制数,要在其基础上只变动一位,也就是只对某一位进行变化,由于格雷码的长度为 n ,这样的变化会有 n 种。
2. 通过 n 次变化产生数值,若 list 中没有该数,就将该数添加到 list 中。同时,以本次产生的新数作为下一轮变动的基础。
这样的算法时间复杂度很高。并不是一种好的解决方法。

通过看大神的解答:http://blog.csdn.net/linhuanmars/article/details/24511221
1. n == 1 时,最基本的数字是 0 和 1,将它们加入到 list 中,作为后续变化的基础。
2. 每一次都在已有数字基础上在其前面(最左端)添加数字 1,使原有数字变成一个新的数。(在最左端添加 0 ,并没有改变原有数字) 因为原有数字互不相同,添加 1 后的数字也各不相同。
3. 在 list 中已有数字的基础上,对 list 中的数从后向前遍历,依次对已有的数字(二进制位数为 k)加上比当前数字位数多一位(k + 1 位)的 数——1 左移 k 位。
举例说明:
第一轮:0 1
第二轮:11 10(新添加) | 1 0(已有) 加上 1 左移 1 位
第三轮:111 110 101 100(新添加)| 11 10 1 0 加上 1 左移 2 位
……

代码实现:
第二种思路:

public class Solution {    public List<Integer> grayCode(int n) {        List<Integer> list = new ArrayList();        if(n == 0) {            list.add(0);            return list;        }        list.add(0);        list.add(1);        for(int i = 2; i <= n; i ++) {            int size = list.size();            for(int j = size - 1; j >= 0; j --)                list.add(list.get(j) + (1 << (i - 1)));        }        return list;    }}
12 / 12 test cases passed.Status: AcceptedRuntime: 1 ms

第一种思路:

public class Solution {    public List<Integer> grayCode(int n) {        int len = (int)Math.pow(2.0, n);        List<Integer> list = new ArrayList();        int k = 0;        while(list.size() < len - 1) {            for(int i = 0; i < n; i ++) {                int temp = k ^ (int)Math.pow(2.0, i);                if(!list.contains(temp)) {                    list.add(k);                    k = temp;                    break;                }            }        }        list.add(k);        return list;    }}
12 / 12 test cases passed.Status: AcceptedRuntime: 16 ms
0 0