Leetcode: Gray Code
The gray code is a binary numeral system where two successive values differ in only one bit.
Given a non-negative integerNRepresenting the total number of BITs in the code, print the sequence of Gray code. A gray code sequence must begin with 0.
For example, givenN= 2, return[0,1,3,2]
. Its Gray code sequence is:
00 - 001 - 111 - 310 - 2
Note:
For a givenN, 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.
Address: https://oj.leetcode.com/problems/gray-code/
Algorithm: assuming that we have completed the first I-bit gray code, we should construct the first I + 1-bit gray according to the following structure: first, the I + 1-bit zero part, the subsequent I-bit is the same as the previous I-bit gray code, followed by the part where I + 1 is 1, the second I-bit is sorted in the reverse order of the first I-bit gray code. If the n = 2gray code is 00 01 11 10, then the Gray Code of N = 3 is 000 001 011 010 110 111 101 100. Code:
1 class Solution { 2 public: 3 vector<int> grayCode(int n) { 4 vector<int> result; 5 if(n < 0) return result; 6 result.push_back(0); 7 if(n == 0) return result; 8 result.push_back(1); 9 for(int i = 1; i < n; ++i){10 int len = result.size();11 int temp = 1 << i;12 for(int j = len-1; j >= 0; --j){13 result.push_back(result[j] + temp);14 }15 }16 return result;17 }18 };
Leetcode: Gray Code