[LeetCode] 89. 格雷编码

题目链接 : https://leetcode-cn.com/problems/gray-code/

题目描述:

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

给定一个代表编码总位数的非负整数 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]。

思路:

维基百科有三种方法

思路一:二进制数转格雷码

即: \(G(n) = B(n+1)\) XOR \(B(n)\)

思路二:镜射排列

思路三:直接排列

扫描二维码关注公众号,回复: 6480702 查看本文章

以二进制为0值的格雷码为第零项,第一项改变最右边的位元,第二项改变右起第一个为1的位元的左边位元,第三、四项方法同第一、二项,如此反复,即可排列出n个位元的格雷码.

代码:

思路一:

class Solution:
    def grayCode(self, n: int) -> List[int]:
        res = []
        for i in range(2 ** n):
            res.append((i >> 1) ^ i)
        return res

java

class Solution {
    public List<Integer> grayCode(int n) {
        List<Integer> res = new ArrayList<>();
        for (int i = 0; i < Math.pow(2, n); i++) {
            res.add((i >> 1) ^ i);
        }
        return res; 
    }
}

思路二:

class Solution:
    def grayCode(self, n: int) -> List[int]:
        res = [0]
        for i in range(n):
            for j in range(len(res) - 1, -1, -1):
                res.append(res[j] ^ (1 << i))
        return res

java

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

思路三:

class Solution:
    def grayCode(self, n: int) -> List[int]:
        num = "0" * n
        res = [0]
        c = 2 ** n
        while len(res) < c:
            if num[-1] == "0":
                num = num[:-1] + "1"
                res.append(int(num, 2))
            else:
                num = num[:-1] + "0"
                res.append(int(num, 2))
            # print(num)

            if len(res) == c:
                break
            idx = num.rfind("1")
            if num[idx - 1] == "0":
                num = num[:idx - 1] + "1" + num[idx:]
            else:
                num = num[:idx - 1] + "0" + num[idx:]
            # print(num)
            res.append(int(num, 2))

        return res

java

class Solution {
    public List<Integer> grayCode(int n) {
        StringBuilder num = new StringBuilder();
        List<Integer> res = new ArrayList<>();
        res.add(0);
        double c = Math.pow(2, n);
        for (int i = 0; i < n; i++) num.append('0');
        while (res.size() < c) {
            if (num.charAt(num.length() - 1) == '0') {
                num.setCharAt(num.length() - 1, '1');
                res.add(Integer.parseInt(num.toString(), 2));
            } else {
                num.setCharAt(num.length() - 1, '0');
                res.add(Integer.parseInt(num.toString(), 2));
            }
            if (res.size() == c) break;
            int idx = num.lastIndexOf("1");
            if (num.charAt(idx - 1) == '0') {
                num.setCharAt(idx - 1, '1');
            } else {
                num.setCharAt(idx - 1, '0');
            }
            res.add(Integer.parseInt(num.toString(), 2));
        }
        return res;     
    }
}

猜你喜欢

转载自www.cnblogs.com/powercai/p/11025874.html