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.


解法一

这道题感觉是一个找规律的题目,找到规律后就非常好求解,感觉不是一道回溯的题。

对于n=2,它的结果包含n=1时的结果左边补零,以及逆序遍历n=1时的结果左边补1。

规律例如以下图,列出了n=1,n=2,n=3时的情况。

依据这个规律假设已知n=k的情况,那么n=k+1的结果包含对n=k的结果左边补零,即保存不变。然后逆序遍历n=k的结果左边补1就可以。

runtime:4ms

class Solution {
public: vector<int> grayCode(int n) {
vector<int> result(1);
for(int i=0;i<n;i++)
{
for(int j=result.size()-1;j>=0;j--)
{
result.push_back((1<<i)+result[j]);
}
}
return result;
}
}。

解法二

解法二就涉及到gray code的数学知识了。要是知道这个数学知识。能够在几分钟之内就解出这道题。

格雷码能够由相应的十进制数求出:grayCode=i^i>>1

runtime:4ms

class Solution {
public:
vector<int> grayCode(int n) {
vector<int> result;
for(int i=0;i<1<<n;i++)
{
result.push_back(i^i>>1);
}
return result;
} };

最新文章

  1. boolean 和 Boolean 类型数据的差别
  2. Installing Lua in Mac
  3. The Services(服务)
  4. GitHub安装失败
  5. MVC4.0系统开发新手历程(一)
  6. php随机函数
  7. 【概率DP入门】
  8. 郁闷的C小加(一)(后缀表达式)
  9. Android调用系统相机、自己定义相机、处理大图片
  10. WebService-03-使用CXF开发服务端和客户端
  11. NET实现仓库看板的一些感想
  12. 关于readonly
  13. SSM-Spring-05:Spring的bean是单例还是多例,怎么改变?
  14. java 中 “==” 和 equals 的区别
  15. 《为大量出现的KPI流快速部署异常检测模型》 笔记
  16. 新建VS工程与填坑:解决方案与项目不在同一目录
  17. DBCO
  18. 前端必须掌握的30个CSS选择器
  19. 告知你不为人知的UDP-疑难杂症和使用
  20. static 成员函数

热门文章

  1. Linux软件安装install命令
  2. python爬取漫画
  3. golang之结构体和方法
  4. Spring Boot Admin Quick Start
  5. 【数据挖掘基础算法】KNN最近邻分类算法
  6. STL中stack/queue/map以及Boost unordered_map 的使用方法
  7. MVC基础知识 – 2.新语法
  8. Java Web开发——HTML CSS JavaScript 杂记
  9. XV6操作系统代码阅读心得(三):锁
  10. vue数据立刻绑定到dom元素