LeetCode89 Gray Code 格雷码生成

本文介绍了两种生成格雷码的方法:一种是通过简单的数学运算直接转换;另一种是迭代生成序列,利用高位变化和序列对称性特性。这两种方法易于理解和实现。

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

1、十进制序列直接得到格雷码 参考:https://www.cnblogs.com/logic3/p/5609919.html

 binary num             gray code
 0=000      000 = 000 ^ (000>>1)
 1=001      001 = 001 ^ (001>>1)
 2=010      011 = 010 ^ (010>>1)
 3=011      010 = 011 ^ (011>>1)
 ...
 7=111      100 = 111 ^ (111>>1)

class Solution {
public:
    vector<int> grayCode(int n) {
        if(n<0) return vector<int>(0);
        
        vector<int> ans;
        int sum = pow(2, n);
        for(unsigned int i=0; i<sum; i++)
        {
            ans.emplace_back(i^(i>>1));
        }
        
        return ans;
    }
};

2、My idea is to generate the sequence iteratively. For example, when n=3, we can get the result based on n=2.
00,01,11,10 -> (000,001,011,010 ) (110,111,101,100). The middle two numbers only differ at their highest bit, while the rest numbers of part two are exactly symmetric of part one. It is easy to see its correctness.
Code is simple:

public List<Integer> grayCode(int n) {
    List<Integer> rs=new ArrayList<Integer>();
    rs.add(0);
    for(int i=0;i<n;i++){
        int size=rs.size();
        for(int k=size-1;k>=0;k--)
            rs.add(rs.get(k) | 1<<i);
    }
    return rs;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值