LeetCode: Gray Code
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.
地址:https://oj.leetcode.com/problems/gray-code/
算法:假设我们已经完成了前面i位的Gray 码,那么前面i+1位Gray应该按如下构造,首先是第i+1位为零部分,其后的i位跟前面i位Gray码一致,然后紧接着是第i+1位为1的部分,其后的i位按前面i位Gray码的逆序排。假如,n=2Gray码为00 01 11 10,那么n=3的Gray码为000 001 011 010 110 111 101 100。代码:
1 class Solution {
2 public:
3 vector<int> grayCode(int n) {
4 vector<int> result;
5 if(n < 0) return result;
6 result.push_back(0);
7 if(n == 0) return result;
8 result.push_back(1);
9 for(int i = 1; i < n; ++i){
10 int len = result.size();
11 int temp = 1 << i;
12 for(int j = len-1; j >= 0; --j){
13 result.push_back(result[j] + temp);
14 }
15 }
16 return result;
17 }
18 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】博客园的心动:当一群程序员决定开源共建一个真诚相亲平台
【推荐】Flutter适配HarmonyOS 5知识地图,实战解析+高频避坑指南
【推荐】凌霞软件回馈社区,携手博客园推出1Panel与Halo联合终身会员
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· C# 锁机制全景与高效实践:从 Monitor 到 .NET 9 全新 Lock
· 一则复杂 SQL 改写后有感
· golang中写个字符串遍历谁不会?且看我如何提升 50 倍
· C# 代码如何影响 CPU 缓存速度?
· 智能桌面机器人:使用 .NET 为树莓派开发 Wifi 配网功能
· 一则复杂 SQL 改写后有感
· 接口被刷百万QPS,怎么防?
· C# 锁机制全景与高效实践:从 Monitor 到 .NET 9 全新 Lock
· 一个开源免费、功能丰富的 WPF 自定义控件资源库
· 提升Avalonia UI质感,跨平台图标库选型实践