【一天一道LeetCode】#89. Gray Code
2016-06-11 17:19
225 查看
一天一道LeetCode
(一)题目
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,生成n位的格雷码。之前做过格雷码的题目,每次都在n-1位格雷码的后面加上0和1组成n位格雷码。
题目中提到只认示例中给定的格雷码顺序。
因此,很容易找到规律,每次从n-1位格雷码的尾部往前,依次加上2的n-1次方,就得到新的n位格雷码。
代码如下:
class Solution { public: vector<int> grayCode(int n) { vector<int> ret; if(n==0) {//为0的时候需要特殊处理 ret.push_back(0); return ret; } for(int i = 0 ; i < n ; i++) { if(i==0)//这里表示1位格雷码 { ret.push_back(0); ret.push_back(1); } else { for(int j = ret.size()-1 ; j >=0 ; j--)//每次从n-1位格雷码的尾部向前,一次加上2的n-1次方得到新的格雷码 { ret.push_back(pow(2,i)+ret[j]); } } } return ret; } };
相关文章推荐
- 【一天一道LeetCode】#89. Gray Code
- Java并发编程-Fork/Join框架同步与异常
- LeetCode-86.Partition List
- java并发编程-- 并发编程大合集
- 基于Redux架构的单页应用开发总结(三)
- Ubuntu下允许远程连接MySQL数据库
- 【实战+视频】在龙芯CPU和中标麒麟系统上装品高云,实现EC2,EIP,VPC等云服务
- Python 返回函数_闭包_装饰器
- c++实践参考:圆柱
- AIDL使用总结
- Length of Last Word
- linux网络编程:使用单进程实现多客户端通信
- R主成分分析与因子分析
- Symfony学习--原创。。。。
- R语言随机森林
- 学习进度14
- 读《程序员的思维修炼》有感
- SpringMVC基于Controller的注解
- JavaWeb学习笔记之Spring中bean的作用域
- CSS学习4(文本属性)