[LeetCode]Gray Code

来源:互联网 发布:应届生求职软件知乎 编辑:程序博客网 时间:2024/06/10 10:08

题目

Number: 89
Difficulty: Medium
Tags: Backtracking

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

题解

求格雷码序列。

根据维基百科-格雷码解释,格雷码是一个数列集合,相邻两数间只有一个位元改变,为无权数码,且格雷码的顺序不是唯一的,n位元的格雷码可以从n-1位元的格雷码以上下镜射后加上新位元的方式快速的得到,如图:

代码

vector<int> grayCode(int n) {    vector<int> res(1, 0);    if(n <= 0)        return res;    int index = 1;    while(n--){        int i = res.size();        while(i--){            res.push_back(res[i] + index);        }        index <<= 1;    }    return res;}
0 0
原创粉丝点击