Problem:
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.
Hide TagsBacktrackingTest instructions: First of all, we need to know the definition of gray code, to find the N-bit gray code, and convert it to int output
Thinking:
(1) In strict accordance with the Gray code definition, gray code has a recursive formula:
Using the above formula can be recursive (backtracking) out of the N-bit gray code, I here use the string processing method to achieve the above formula, the same principle.
Code
Class solution {public:vector<int> Graycode (int n) {vector<int> ret; if (n==0) {ret.push_back (0); return ret; } if (n==1) {ret.push_back (0); Ret.push_back (1); return ret; } if (n==2) {ret.push_back (0); Ret.push_back (1); Ret.push_back (3); Ret.push_back (2); return ret; } vector<string> GC2; Gc2.push_back (String ("00")); Gc2.push_back (String ("01")); Gc2.push_back (String ("11")); Gc2.push_back (String ("10")); Vector<string> GC (GC2); int length=4; for (int i=3;i<=n;i++) {length*=2; Vector<string> gc_tmp (Length,string ("")); for (int j=0;j<length/2;j++) {string str0= "0" +gc[j]; String str1= "1" +gc[length/2-j-1]; GC_TMP[J]=STR0; GC_TMP[J+LENGTH/2]=STR1; } gc=gc_tmp; } for (int i=0;i<gc.size (); i++) Ret.push_back (String_to_int (Gc[i])); return ret; }protected:int string_to_int (String str) {cout<<str<<endl; int m=str.size (); Double res=0; for (int i=0;i<m;i++) {res+= (str.at (i)-' 0 ') *pow (2,m-i-1); } return int (res); }};
Leetcode | | 89. Gray Code