您的位置:首页 > 其它

89. Gray Code #Medium

2016-06-08 10:46 441 查看
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++代码

[code]class Solution {
public:
vector grayCode(int n) {
vector r1(1,0),r2;
if(n
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: