leetcode 89: Gray Code

本文介绍了两种生成格雷码的算法实现。一种是通过检查每个数是否存在来生成,另一种是使用位运算进行更简洁的实现。后者利用掩码和位移操作逐步构建格雷码序列。

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

class Solution {
public:
    vector<int> grayCode(int n) {
        vector<int> res;
        map<int,bool> mp;//check whether a number is existed
        res.push_back(0);
        if(n==0)
            return res;
        mp[0]=1;
        vector<int> cal(n);//save as 1,2,4,8,...
        cal[0]=1;
        for(int i=1;i<n;i++)
            cal[i]=cal[i-1]*2;
        int num=0;
        int i=0;
        while(i<n)
        {
            int temp=num^cal[i];
            if(mp.find(temp)==mp.end())
            {
                mp[temp]=1;
                res.push_back(temp);
                num=temp;
                i=0;
            }
            else
                i++;
        }
        return res;
    }
};


A simpler way to do it

class Solution {
public:
    vector<int> grayCode(int n) {
        vector<int> res;
        res.push_back(0);
        if(n==0)
            return res;
        int mask=1;
        while(res.size()!=1<<n)
        {
            int len=res.size();
            for(int i=len-1;i>=0;i--)
                res.push_back(mask|res[i]);
            mask=mask<<1;
        }
        return res;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值