首页 > 代码库 > LeetCode: Gray Code

LeetCode: Gray Code

LeetCode: 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 - 001 - 111 - 310 - 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.

地址:https://oj.leetcode.com/problems/gray-code/

算法:假设我们已经完成了前面i位的Gray 码,那么前面i+1位Gray应该按如下构造,首先是第i+1位为零部分,其后的i位跟前面i位Gray码一致,然后紧接着是第i+1位为1的部分,其后的i位按前面i位Gray码的逆序排。假如,n=2Gray码为00 01 11 10,那么n=3的Gray码为000 001 011 010 110 111 101 100。代码:

 1 class Solution { 2 public: 3     vector<int> grayCode(int n) { 4         vector<int> result; 5         if(n < 0)   return result; 6         result.push_back(0); 7         if(n == 0)  return result; 8         result.push_back(1); 9         for(int i = 1; i < n; ++i){10             int len = result.size();11             int temp = 1 << i;12             for(int j = len-1; j >= 0; --j){13                 result.push_back(result[j] + temp);14             }15         }16         return result;17     }18 };

 

LeetCode: Gray Code