Gray Code

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.

For example, given n = 2, return [0,1,3,2]. Its gray code sequence is:

00 - 0
01 - 1
11 - 3
10 - 2

Note:
For a given n, a gray code sequence is not uniquely defined.

For example, [0,2,3,1] is also a valid gray code sequence according to the above definition.

For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that.

C++:
01 class Solution {
02 public:
03     vector<int> grayCode(int n) {
04         // Start typing your C/C++ solution below
05         // DO NOT write int main() function
06         vector<int> result;
07         result.push_back(0);
08         int m=1;
09         for(int i=1;i<=n;i++)
10         {
11             int r=result.size();
12             for(int j=r1;j>=0;– –)
13             {
14                 result.push_back(result[j]+m);
15             }
16             m*=2;
17         }
18         return result;
19     }
20 };
Advertisements
This entry was posted in Dynamic programming. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s