Topic:
The gray code is a binary numeral system where the successive values are 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, was [0,2,3,1]
also a valid gray code sequence according to the above definition.
For now, the judge are able to judge based on one instance of gray code sequence. Sorry about that.
When N=3, Graycode is:
000001011010110111101100
Ideas:
The gray code of n bits can be obtained from the Gray code of the n-1 bit,
N-bit gray code consists of:
1, n-1 bit of gray code
2, n-1 bit of gray code in reverse order + (1<< (n-1))
Such as:
Code:
#include <iostream>#include<vector>using namespacestd;//non_recursivevector<int> Graycode_1 (intN) {Vector<int>result; Result.push_back (0); for(intI=0; i<n;i++){ intlen=result.size (); intC=1<<i; for(intj=len-1; j>=0; j--) Result.push_back (Result[j]+c); } returnresult;}//RecursivevoidGraycode_2 (vector<int> &result,intN) { if(n==0) {Result.push_back (0); return; } graycode_2 (Result,n-1); intlen=result.size (); for(inti=len-1; i>=0; i--) Result.push_back (Result[i]+(1<< (n1)));}intMain () {intn=4; Vector<int>RESULT1; Vector<int>result2; RESULT1=graycode_1 (n); Graycode_2 (Result2,n); for(intI=0; I<result1.size (); i++) cout<<result1[i]<<" "; cout<<Endl; for(intI=0; I<result2.size (); i++) cout<<result2[i]<<" "; cout<<Endl; return 0;}
Gray Code (algorithm)