题目:
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 - 2Note:
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.
就是把n位二进制数都转成十进制返回。代码:
1 vector<int> grayCode(int n) { 2 vector<int> result; 3 if(!n) { 4 result.push_back(0); 5 return result; 6 } 7 bool* bits = (bool*)malloc(n); 8 memset(bits,0,n); 9 getGrayCode(result,n,0,bits); 10 return result; 11 } 12 void getGrayCode(vector<int>& result,int n,int i,bool* bits){ 13 if(n==i){ 14 result.push_back(b2i(bits,n)); 15 return ; 16 } 17 getGrayCode(result,n,i+1,bits); 18 bits[i]=!bits[i]; 19 getGrayCode(result,n,i+1,bits); 20 } 21 int b2i(bool* bits,int n){ 22 int result=0,c=0; 23 for(int i=n-1;i>=0;i--){ 24 if(!c) c=1; 25 else c*=2; 26 if(bits[i]){ 27 result += c; 28 } 29 } 30 return result; 31 }
时间复杂度太大了,以为过不了,结果还是过了,都2n*n了。不过规模已经是指数级,没办法降啊。
后来看到这个解法,于是去wikipedia上面看了下,确实非常简单,下面的链接:
http://blog.csdn.net/doc_sgl/article/details/12251523