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 (Medium)
For example, given n = 2, return [0,1,3,2]
. Its gray code sequence is:
00-001-111-310-2
Analysis:
Examine the three-bit gray code and the two-bit gray code as follows:
00 01 11 10;
000 001 011 010 110 111 101 100;
You can see the following rules, three-bit gray code is two-bit gray code front plus 0, and reverse two-dimensional gray code front plus 1 get.
So ask N for the gray code, only need to add 0 in front of all n-1 bits, and 1 in the reverse of all the n-1-bit gray code.
Code:
1 classSolution {2 Public:3vector<int> Graycode (intN) {4 if(n = =0) {5 returnvector<int> {0};6 }7vector<int> temp = Graycode (n-1);8vector<int>result;9 for(inti =0; I < temp.size (); ++i) {Ten Result.push_back (Temp[i]); One } A for(inti = temp.size ()-1; I >=0; --i) { -Result.push_back (Temp[i] + POW (2N1)); - } the returnresult; - } -};
LeetCode89 Gray Code