• [leetcode] Grey Code


    题目:(Backtracking)

    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.

    题解:

    参考引用http://www.lifeincode.net/programming/leetcode-gray-code-java/

    We can see that the last two digits of 4 codes at the bottom is just the descending sequence of the first 4 codes. The first 4 codes are 0, 1, 3, 2. So, we can easily get the last 4 codes: 2 + 4, 3 + 4, 1 + 4, 0 + 4, which is 6, 7, 5, 4. We can keep doing this until we reach n digits.

    要解决这个问题先看一下greycode的规律

    当n=1:

    0

    1

    当n=2:

    00

    01

    11

    10

    当 n = 3:

    000
    001
    011
    010
    110
    111
    101
    100

    然后我们可以发现一个规律,当n每增加1的时候,

    其实就是:1.把n-1的所有元素前面加上一个0.  2.将n-1的所有元素倒序排列以后前面加上1。

    例如当 n=2时 n-1 为 

    0

    1

    所有第一步将n-1的所有元素前面加上一个0

    00

    01

    第二步将n-1的所有元素倒序排列以后前面加上1

    11

    10

    然后因为要转化成十进制的数,第一步前面加0,就是加0,就是什么都不要加。第二步前面要加1,正好就是加上 n-1 的所有元素的 数目。

    所以代码如下:

    public class Solution {
        public List<Integer> grayCode(int n) {
            List<Integer> ret = new LinkedList<>();
            ret.add(0);
            for (int i = 0; i < n; i++) {
                int size = ret.size();
                for (int j = size - 1; j >= 0; j--)
                    ret.add(ret.get(j) + size);
            }
            return ret;
        }
    }
  • 相关阅读:
    ArrayList和CopyOnWriteArrayList
    UML类关系
    Vmware下mint os的安装
    Java VisualVM无法检测到本地java程序 的 解决办法
    谜之闭包
    虚拟DOM(Virtual DOM)
    ES6箭头函数与普通函数的区别
    HTML中 select 与datalist的异同
    备战前端面试
    javascript获取数组中的最大值/最小值
  • 原文地址:https://www.cnblogs.com/fengmangZoo/p/4185870.html
Copyright © 2020-2023  润新知