Tag: style blog color Io AR for SP Div 2014
When it comes to Gray Code, no one knows how to use it. I am not very clear about it. My roommate should be an expert. The generation rule is not very obvious. As I saw in my post, I cannot find it now ..
This is the idea. If there are N bits and draw a horizontal line below the 2nd ^ (n-1) code, you will find that, except for the first bit, other bits are symmetric about this line, the following example uses a three-digit Gray code:
000
001
011
010
---------------------
110
111
101
100
It's amazing. I used to know this rule. From the beginning of a gray code, 0, 1, start, each symmetric add 0 and 1 in front of the previous one, get all gray codes of the next length.
I did not write this question so much, and I was a little lazy. Due to another more concise method, I have not yet thoroughly understood the detailed principle. Should it be the method used for Gray Code definition? The code is pasted below:
class Solution {public: vector<int> grayCode(int n) { vector<int> res; if(n == 0){ res.push_back(0); }else{ for(int i=0;i<pow(2, n);i++) res.push_back((i>>1)^i); } return res; }};
Leetcode first _ Gray Code