Leetcode 89(Java)

来源:互联网 发布:软件开发很难吗 编辑:程序博客网 时间:2024/06/05 18:24

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.

格雷码的知识在数字电路里学习过,老师当时就讲了镜像的规律,例如当n=1时,result里有0,1。当n=2时,result里为00,01,11,10,当 n不断累加,我们不难发现,每一个n对应的结果,可以讲上一个n-1对应结果里的内容复制一份,然后在前一份最高位+0,后一份最高位+1。既然每一个n的结果都是与n-1相关,不难想到用 回溯法。AC码如下:

public class Solution {    public List<Integer> grayCode(int n) {        if(n==0){            List<Integer> result = new ArrayList<>();            result.add(0);            return result;        }        List<Integer> result = grayCode(n-1);        int originSize = result.size();        int addN = 1 << (n-1);        for(int i = originSize-1;i>=0;i--)            result.add(addN+result.get(i));        return result;    }}