LeetCode——Gray Code

本文介绍两种生成格雷码序列的方法。一种是递归构造法,通过递归将n位格雷码转换为n+1位格雷码;另一种是直接计算法,利用位运算快速生成格雷码序列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

  • Example 1:
    Input: 2
    Output: [0,1,3,2]
    Explanation:
    00 - 0
    01 - 1
    11 - 3
    10 - 2
    For a given n, a gray code sequence may not be uniquely defined.
    For example, [0,2,3,1] is also a valid gray code sequence.
    00 - 0
    10 - 2
    11 - 3
    01 - 1
  • Example 2:
    Input: 0
    Output: [0]
    Explanation: We define the gray code sequence to begin with 0.
    A gray code sequence of n has size = 2n, which for n = 0 the size is 20 = 1.
    Therefore, for n = 0 the gray code sequence is [0].

解法

当n=0时,返回{0},当n=1时,返回{0,1}
当n==2时:
0 0-----0
0 1-----1


1 1-----3
1 0-----2

当n==3时:
0 0 0-----0
0 0 1-----1
0 1 1-----3
0 1 0-----2


1 1 0-----6
1 1 1-----7
1 0 1-----5
1 0 0-----4

由此可得n的数列为:n-1的数列加上n-1数列反过来排,并给每一个数加2的n-1次幂。
讲起来有点麻烦啊,还是偷个图吧
在这里插入图片描述

public List<Integer> grayCode(int n) {
		return grayCodecore(n);
	}

	private List<Integer> grayCodecore(int n) {
		// TODO Auto-generated method stub
		List<Integer> list = new ArrayList<Integer>();
		if (n == 0)
			list.add(0);
		else if (n == 1) {
			Integer[] array = { 0, 1};
			Collections.addAll(list, array);
		} else {
			list = grayCodecore(n - 1);
			for (int i = list.size() - 1; i >= 0; i--)
				list.add((int) (list.get(i) + Math.pow(2, n - 1)));
		}
		return list;
	}

Runtime: 1 ms, faster than 44.03% of Java online submissions for Gray Code.
Memory Usage: 33 MB, less than 100.00% of Java online submissions for Gray Code.

解法二

Int    Grey Code    Binary    Binary>>1
 0      000        000         000
 1      001        001         000
 2      011        010         001
 3      010        011         001
 4      110        100         010
 5      111        101         010
 6      101        110         011
 7      100        111         011

可见格雷码为i和i右移一位的异或

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

Runtime: 0 ms, faster than 100.00% of Java online submissions for Gray Code.
Memory Usage: 32.9 MB, less than 100.00% of Java online submissions for Gray Code.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值