Gray Code问题及分析

来源:互联网 发布:万网购买域名能退款吗 编辑:程序博客网 时间:2024/05/17 01:39

问题描述:

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.

示例:

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.


问题分析:

通过分析规律可得如下两种解决方法:

①G(i) = i ^ (i / 2);

②先把原数组分成两份,左边的先保留,右边的数组再分成两份a和b,a和b互换位置;以此回溯,直到 n = 1结束。


过程详见代码(②):

class Solution {public:    vector<int> grayCode(int n) {vector<int> res;        n = (int)pow(2, n);for (int i = 0; i < n; i++)res.push_back(i);sortGrayCode(res, n, 0);return res;}void sortGrayCode(vector<int>& res,int n,int start){if (n == 1) return;sortGrayCode(res, n / 2, start);for (int i = start + n / 2; i < start + n / 2 + n / 4; i++)swap(res[i], res[i + n / 4]);sortGrayCode(res, n / 2, start + n / 2);}};