leetcode 89. Gray Code #Medium
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
题意:
根据所给数字n生成2^n个连续的格雷码
分析:
举例
n=1, [0, 1]
n=2, [00, 01, 11, 10]
n=3, [000, 001, 011, 010, 110, 111, 101, 100]
后一个序列的前半段就是前一个序列,后半段是前一个序列的每个数字左边补1,然后反向排列这些数字。根据此规律可求解
C++代码:
class Solution {
public:
vector
grayCode(int n) {
vector
r1(1,0),r2;
if(n<1)return r1;
r1.push_back(1);
for(int i=1,j;i
=0;j--)r2.push_back(r1[j]+(1<