LeetCode Gray Code
来源:互联网 发布:ck jeans 知乎 编辑:程序博客网 时间:2024/06/08 11:12
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 - 001 - 111 - 310 - 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.
以3位格雷码为例。
0 0 0
0 0 1
0 1 1
0 1 0
1 1 0
1 1 1
1 0 1
1 0 0
可以看到第n位的格雷码由两部分构成,一部分是n-1位格雷码,再加上 1<<(n-1)和n-1位格雷码的逆序的和
class Solution {public: vector<int> grayCode(int n) { if(n==0) { vector<int>ret; ret.push_back(0); return ret; } else { vector<int>tmp=grayCode(n-1); vector<int>ret; for(int i=0;i<tmp.size();++i) { ret.push_back(tmp[i]); } for(int i=tmp.size()-1;i>=0;--i) { ret.push_back((1<<(n-1))+tmp[i]); } return ret; } }};
0 0
- LeetCode: Gray Code
- [LeetCode] 格雷码(Gray Code)
- LeetCode Gray Code
- [Leetcode] Gray Code
- [LeetCode] Gray Code
- leetcode 112: Gray Code
- LeetCode Gray Code
- [leetCode] Gray Code
- [LeetCode]Gray Code
- Leetcode: Gray Code
- [leetcode]Gray Code
- LeetCode-Gray Code
- [leetcode] Gray Code
- LeetCode - Gray Code
- leetcode之Gray code
- LeetCode:Gray Code
- 【转载】【leetcode】Gray Code
- LeetCode - Gray Code
- objdump命令的使用
- GUI用法
- POJ 1508-------Skyscraper Floor
- java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.<init>
- 用ORACLE的高级复制实现内外网数据同步
- LeetCode Gray Code
- SDRAM的tRCD、CL、tAC的定义
- Java代码性能调优的相关优秀文章
- IOS开发---OC语言-㉒@property模型设计练习
- UML关系(泛化,实现,依赖,关联(聚合,组合))
- TCP/UDP相关
- GUI(打开、保存文件)
- Library
- Editplus配置Java运行环境