[LeetCode]Gray Code

本文详细介绍了灰码生成的原理与实现方法,通过构建有效的模式,利用递归思想和位运算技巧,实现了从任意长度到指定长度的灰码序列生成。包括核心算法解析、代码实现与验证过程。
class Solution {
//write down some cases, and try to find out the regular pattern
//gray code is not unique, so we should find out at least one regular pattern
//one of these regular pattern is that:
//let f(i) be the gray code sequence when n=i,
//then the number of sequence f(i+1) is twice of f(i), we consider f(i) is a half sequence of f(i+1)
//because the sequence f(i) is valid, so another half valid sequence can be find to add 1 in the highest bit of each element of f(i), 
//the last thing we need to figure out is that we should concatenate these two sequence, the last one element of the second half will be 
//only one digit different from the last of the first half, so we just need to reverse the second half
public:
	vector<int> grayCode(int n) {
		// Start typing your C/C++ solution below
		// DO NOT write int main() function
		vector<int> ans;
		ans.push_back(0);
		for (int i = 1; i <= n; ++i)
		{
			int size = ans.size();
			for (int j = size-1; j >= 0; --j)
				ans.push_back( ans[j]^(1<<(i-1)) );
		}
		return ans;
	}
};

second time

class Solution {
public:
    vector<int> grayCode(int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<int> ans(1);
        ans[0] = 0;
        int add = 1;
        for(int i = 1; i <= n; ++i)
        {
            int oldSize = ans.size();
            for(int j = oldSize-1; j >= 0; --j) ans.push_back(ans[j]+add);
            add *= 2;
        }
        return ans;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI记忆

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值