Skip to content

Instantly share code, notes, and snippets.

@pdu
Created January 9, 2013 15:43
Show Gist options
  • Select an option

  • Save pdu/4494139 to your computer and use it in GitHub Desktop.

Select an option

Save pdu/4494139 to your computer and use it in GitHub Desktop.
The gray code is a binary numeral system where two successive values 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. http://leetcode.com/onlinejudge
class Solution {
public:
vector<int> grayCode(int n) {
vector<int> ret;
if (n == 0) {
ret.push_back(0);
return ret;
}
else if (n == 1) {
ret.push_back(0);
ret.push_back(1);
return ret;
}
else {
vector<int> tmp = grayCode(n - 1);
ret = tmp;
for (int i = tmp.size() - 1; i >= 0; --i)
ret.push_back(tmp[i] + ( 1 << (n - 1)));
return ret;
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment