一.问题描述
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];
}
}
};