【Leetcode】之Gray Code
2016-07-21 23:05
393 查看
一.问题描述
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.
二.我的解题思路
拿到题目观察一番,就不难想到可以用分治递归的算法思想去解决。具体实现起来也比较容易,测试通过的程序如下:class Solution {
public:
vector<int> grayCode(int n) {
vector<int> res(pow(2.0,n),0);
if(n<=0) return res;
gen_code(res,n);
return res;
}
void gen_code(vector<int>& res,int n){
if(n==1){
res[0]=0;
res[1]=1;
return;
}
int curr_num=pow(2.0,n-1);
gen_code(res,n-1);
for(int i=curr_num;i<2*curr_num;i++){
res[i]=pow(2.0,n-1)+res[2*curr_num-i-1];
}
}
};
相关文章推荐
- 工作情感2-关于UE总监的一些思考
- MySQL优化
- POJ 1502 MPI Maelstrom 【单源最短路中求最大值】
- 特殊正则表达式
- 特殊正则表达式
- java-基础-关键字
- 字典类型
- H.264量化参数QP和量化步长Qstep
- Java中有两种实现多线程的方式以及两种方式之间的区别
- express 解析post方式下的json参数
- http状态码解析
- http状态码解析
- Oracle学习 用户、权限、角色
- 自定义View之尺寸的转化
- 华为721----Java8新特性_
- OSX: BootCamp和Win 7或者Win 10使用的MBR不同
- 查找最大元素 hd 2025
- Linux 的 NUMA 技术
- 写一个控制台运行的计算器
- Ubuntu下adb 调试找不到device