LeetCode刷题笔录Gray Code

本文介绍了一种生成格雷码序列的有效算法。该算法通过递增地构建更高位数的格雷码序列来实现,利用反转和位移操作简化过程。以n=2为例,展示了如何生成对应的格雷码,并扩展到任意位数。

摘要生成于 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.

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.


看看wikipedia的词条就知道这题是怎么回事了。

n=2时候的gray code

00 01 11 10

其反转是

10 11 01 00

而n = 3时候的gray code就是把n=2的gray code前面加上一个0:

000 001 011 010

以及n=2的反转前面加上1:

110 111 101 100

然后把上面的两个List合起来:

000 001 011 010 110 111 101 100

所以这就简单了:integer有32位,所以前面加0可以不用操作,直接把n-1的list拿过来用;前面加1只要反转n-1的list并加上1<<n即可。

public class Solution {
    public List<Integer> grayCode(int n) {
        List<Integer> res = new ArrayList<Integer>();

        res.add(0);
        
        for(int i = 0; i < n; i++){
            int header = 1 << i;
            int length = res.size();
            
            for(int j = length - 1; j >= 0; j--){
                res.add(res.get(j) + header);
            }
        }
        
        return res;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值