Stay button 89-- Gray code

The original title

Gray code is a binary number system, in this system, only two successive values ​​of a difference in number of bits.

Given a total number of bits representing an encoded non-negative integer n, which is the print gray coding sequence. Gray coding sequence must begin with 0.

Example 1:

输入: 2
输出: [0,1,3,2]
解释:
00 - 0
01 - 1
11 - 3
10 - 2

对于给定的 n,其格雷编码序列并不唯一。
例如,[0,2,3,1] 也是一个有效的格雷编码序列。

00 - 0
10 - 2
11 - 3
01 - 1

Example 2:

输入: 0
输出: [0]
解释: 我们定义格雷编码序列必须以 0 开头。
     给定编码总位数为 n 的格雷编码序列,其长度为 2n。当 n = 0 时,长度为 20 = 1。
     因此,当 n = 0 时,其格雷编码序列为 [0]。

原题url:https://leetcode-cn.com/problems/gray-code/

Problem-solving

The initial idea

Beginning to get this title, I am thinking of starting at 0, each time starting from the first change to the right, into the result set (collection), add if successful, the current number as a new starting point, continue to change and add otherwise, it changes the next.

The idea may seem nice, actually there are two difficulties need to be addressed:

  1. How to ensure the conversion of a binary, accurate modify each one? If you use a for loop, it is inefficient.
  2. Each time such a change, is likely to be low efficiency, time complexity will be high, how to optimize?

Based on the above two points, I tried a little bit, I feel this method is not reliable, decided to change a line of thought.

Find the law

So, now I'll try to look for the laws themselves to write about 0, 1, 2, 3 Gray-coded:

0位:
0

1位:
0
1

2位:
00
01
11
10

3位:
000
001
011
010
110
111
101
100

After writing, you should be able to find the following rules:

  1. The first n-bit Gray code are a subset of the n + 1-bit Gray coded, means may be utilized on a result.
  2. In accordance with binary point of view, each one more, in fact, that in many position to 1.
  3. Based on point 2, you need to do to add, Gray coding is required to consider the order, and can not simply be set, it should be the last set of results for reverse output and 1 at the highest position.

3 above the law, only the last rule, may be more difficult to find, but taking into account the characteristics of the order, should be able to get out. Next we look at the code:

class Solution {
    public List<Integer> grayCode(int n) {
        // 动态规划,第n种情况是由:第n-1种正序各数字前加0 + 第n-1种倒序各数字前加1

        // 先给出一开始的情况
        LinkedList<Integer> list = new LinkedList<>();
        list.add(0);
        if (n == 0) {
            return list;
        }

        LinkedList<Integer> result = new LinkedList<>();
        result.add(0);
                // 最高位置1,可以理解为增加
        int add = 1;
        for (int i = 1; i <= n; i++) {
            // 倒序
            Collections.reverse(list);
            for (int item : list) {
                result.add(item + add);
            }

            list = new LinkedList<>(result);
            add = add << 1;
        }

        return result;
    }
}

Submit OK, when executed by: 3 msmemory consumption: 34.5 MBbut only overcome when using 9.59%the java commit record, it seems there is optimization necessary.

optimization

I first thought of optimization is 倒序, I do not really need to be the last set of results is really upside down, but as long as you can traverse in reverse order. Because my result set is stored in the LinkedList, it can be used descendingIterator, directly reverse traversal, its code is:

class Solution {
    public List<Integer> grayCode(int n) {
        // 动态规划,第n种情况是由:第n-1种正序各数字前加0 + 第n-1种倒序各数字前加1

        // 先给出一开始的情况
        LinkedList<Integer> list = new LinkedList<>();
        list.add(0);
        if (n == 0) {
            return list;
        }

        LinkedList<Integer> result = new LinkedList<>();
        result.add(0);
        int add = 1;
        for (int i = 1; i <= n; i++) {
            // 倒序
            Iterator<Integer> descIterator = list.descendingIterator();
            while (descIterator.hasNext()) {
                result.add(descIterator.next() + add);
            }

            list = new LinkedList<>(result);
            add = add << 1;
        }

        return result;
    }
}

Submit OK, when executed by: 2 msmemory consumption: 34.3 MBbut only overcome when using 21.07%the java submit records, it appears you can also continue to optimize.

Continue to optimize

This time I was eyeing list = new LinkedList<>(result);, appears to be one line of code, the actual internal use of the addAllmethod, still need to traverse the result set. All you have to define a new set of results is to record intermediate results, if it really necessary?

If you still use LinkedList structure, you really need to create the result set. Because it wants to get intermediate results with get(int index)this method, still need to traverse. At this time I thought, it can change a data structure ArrayList, so that both the reverse traversal or added, as long as one is on the total number of records, you can achieve the same effects. Let's look at the code:

class Solution {
    public List<Integer> grayCode(int n) {
        // 动态规划,第n种情况是由:第n-1种正序各数字前加0 + 第n-1种倒序各数字前加1

        // 先给出一开始的情况
        ArrayList<Integer> list = new ArrayList<>(1 << n);
        list.add(0);
        if (n == 0) {
            return list;
        }

        int add = 1;
        int tempCount;
        for (int i = 1; i <= n; i++) {
            tempCount = list.size();
            // 倒序
            for (int j = tempCount - 1; j >= 0; j--) {
                list.add(2 * tempCount - j - 1, list.get(j) + add);
            }
            
            add = add << 1;
        }

        return list;
    }
}

Submit OK, when executed by: 1 msmemory consumption: 34.2 MBto overcome when using 97.89%the java submit records, this should be the case.

to sum up

This question is above my answer process, I do not know if you understand. The purpose of this question lies in the difficulty to find the law, and after optimization.

Are interested can visit my blog or follow me number of public, headline number, maybe there will be surprises.

https://death00.github.io/

Public number: Jian Cheng Road

Guess you like

Origin www.cnblogs.com/death00/p/12119291.html