Leetcode 89. Gray Code
2017-02-02 07:42
495 查看
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.
s思路:
1. 方法1:iterative。双重循环,外循环负责增加宽度,内循环复责增加长度。
2. 方法2:recursive,做的过程是:为得到n比特的gray code,先构造n-1比特,所以整个过程是可迭代的,且迭代最底层是n==0,return {0};
3. 做的过程是先想到iterative,反而忽略了recursive。其实越是规则的构造,用recursive越方便简单!复杂的构造,还是iterative好用!不同的题,不同的方法,不过最好都试一试,建立一种直观的sense。每次遇到题,依靠sense就可以解决!
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.
s思路:
1. 方法1:iterative。双重循环,外循环负责增加宽度,内循环复责增加长度。
2. 方法2:recursive,做的过程是:为得到n比特的gray code,先构造n-1比特,所以整个过程是可迭代的,且迭代最底层是n==0,return {0};
3. 做的过程是先想到iterative,反而忽略了recursive。其实越是规则的构造,用recursive越方便简单!复杂的构造,还是iterative好用!不同的题,不同的方法,不过最好都试一试,建立一种直观的sense。每次遇到题,依靠sense就可以解决!
//方法1:iterative。双重循环。 class Solution { public: vector<int> grayCode(int n) { // vector<int> res; if(n<0) return res; res.push_back(0); int j=0; while(j<n){ int i=res.size()-1; while(i>=0){ res.push_back(res[i]+(1<<j)); i--; } j++; } return res; } }; //方法2:用recursive的方法来做!参考了以前做的 class Solution { public: vector<int> grayCode(int n) { // if(n==0) return {0}; vector<int> res=grayCode(n-1); int n0=res.size(); res.resize(1<<n); int n1=res.size(); for(int i=n0;i<n1;i++){ res[i]=res[--n0]+(1<<(n-1)); } return res; } };
相关文章推荐
- [leetcode] 【数组】 89. Gray Code
- LeetCode | 89. Gray Code
- LeetCode 89 Gray Code
- Leetcode 89. Gray Code 格雷码 解题报告
- leetcode题解-89. Gray Code
- LeetCode 89. Gray Code(格雷码)
- LeetCode89——Gray Code
- *LeetCode 89. Gray Code 规律题
- LeetCode 89: Gray Code解题报告
- 【LeetCode】89. Gray Code (2 solutions)
- [LeetCode 89] Gray Code (格雷码问题)
- LeetCode89 Gray Code
- leetcode 89:Gray Code
- leetcode 89. Gray Code
- (java)leetcode-89:Gray Code
- leetcode 89. Gray Code 按照index递归DFS解决 + Grey码生成公式 + 位运算直接计算
- LeetCode89:Gray Code
- LeetCode_89_Gray Code 格雷码
- [leetcode-89]Gray Code(c++)
- LeetCode 89. Gray Code(生成格雷码)