您的位置:首页 > 其它

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就可以解决!

//方法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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: