Created
January 9, 2013 15:43
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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