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.
Take 3-bit 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
You can see that the nth bit of gray code consists of two parts, part of the n-1, plus the reverse of 1<< (n-1) and n-1 bit gray code
Class Solution {public: vector<int> graycode (int n) { if (n==0) { vector<int>ret; Ret.push_back (0); return ret; } else { vector<int>tmp=graycode (n-1); vector<int>ret; for (int i=0;i<tmp.size (); ++i) { ret.push_back (tmp[i]); } for (int i=tmp.size () -1;i>=0;--i) { Ret.push_back ((1<< (n-1)) +tmp[i]); } return ret;}} ;
Leetcode Gray Code