LeetCode-89.格雷编码(相关话题:回溯)

格雷编码是一个二进制数字系统,在该系统中,两个连续的数值仅有一个位数的差异。

给定一个代表编码总位数的非负整数 n,打印其格雷编码序列。格雷编码序列必须以 0 开头。

示例 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

示例 2:

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

解题思路:输入为n的格雷编码序列长度为2的n次方(取值范围为0~2^n-1)。

用数组boolean[2^n] f,f[i]记录i是否已经在格雷编码序列中

产生格雷编码的过程如下(从0开始):

  1. 将0存入结果list中,并将f[0]置为true,cur = 0;
  2. 对当前元素cur(初始时为0)的二进制形式从低位到高位按位取反(一次处理一个二进制位)
  3. 判断新产生的元素next是否已经在格雷编码序列中(即f[next]是否为true)
  4. 若f[next] == true,跳回步骤2
  5. 若f[next] == false,将next存入结果list中,判断结果list长度是否为2^n,若小于2^n,cur = next,跳回步骤2,若等于2^n,return

Java代码:

class Solution {
    public List<Integer> grayCode(int n) {
        int len = (int)Math.pow(2, n);
        List<Integer> res = new ArrayList<>(len);

        res.add(0);
        if(0 < n){
            boolean[] f = new boolean[len];
            int[] code = new int[n];
            f[0] = true;
            dfs(code, f, len , res);
        }

        return res;
    }
    private void dfs(int[] code, boolean[] f, int len, List<Integer> res){
        for(int i = 0; i < code.length; i++){
            code[i] = 1 - code[i];
            int s = toInt(code);
            if(!f[s]){
                res.add(s);
                f[s] = true;
                if(res.size() < len)
                    dfs(code, f, len, res);
            } else {
                code[i] = 1 - code[i];
            }
        }
    }
    private int toInt(int[] code){
        int res = 0;
        for(int i = code.length-1; i >= 0; i--){
            res += code[i] * (int)Math.pow(2, code.length-1-i);
        }
        return res;
    }
}

这里提供两种其他思路:

  1. 找规律,格雷编码有一定的规律,找到规律后可无需回溯(感觉这种做法做出来没什么意义)
  2. 格雷编码的数学知识

有兴趣的可以参考这篇文章:https://blog.csdn.net/u012501459/article/details/46790683

猜你喜欢

转载自blog.csdn.net/weixin_38823568/article/details/82844864