Leetcode: Gray Code
I. Question
Input n to output the Gray code of this number.
For example, input 2 and return {0, 1, 3, 2}
Ii. Analysis
1. Binary Code-> gray code (encoding): Starting from the rightmost bit, each bit is in turn different from the one on the left or (XOR ), as the value corresponding to the gray code, the leftmost digit remains unchanged (equivalent to 0 on the left); (corresponding to the loop body in the for loop of the above Code ).
Gray code-> binary code (Decoding): Each decoded value is different from the decoded value of the second digit on the left or, the decoded value (the leftmost one remains unchanged ).
2. Search for rules
Take the three-digit Gray Code as an example.
0 0 0
0 0 1
0 1 1
0 1 0
1 1 0
1 1 1
1 0 1
1 0 0
We can see that the nth Gray Code consists of two parts: one part is the n-1 Gray code, plus the inverse sum of the 1 <(n-1) and n-1 Gray Codes.
As follows:
(0) 00
(0) 01
(0) 11
(0) 10
100 + 010 = 110
100 + 011 = 111
100 + 001 = 101
100 + 000 = 100
class Solution {public: vector
grayCode(int n) { int num = 1<
ans;ans.reserve(num);for(int i=0;i
>1));return ans; }};
class Solution {public: vector
grayCode(int n) { vector
ans; if(n==0){ ans.push_back(0); return ans; } vector
res = grayCode(n-1); int len = res.size()-1; int adder = 1<<(n-1); for(int i=len;i>=0;i--){ res.push_back(adder+res[i]); } return res; }};