Gray Code LeetCode 89

题目: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

这道题其实就是产生格雷码(简直废话~),格雷码是有一定规律的,数电课上学过一点格雷码的规律,但是对于编程解决问题没啥用啊- -,我们还是来找规律吧。4位的,我手写最多写4位
0000
0001
0011
0110
0111
0101
0100
1100
1101
1111
1110
1010
1011
1001
1000
按列来看,从左往右数第0列(从0列开始),前半部分为0,后半部分为1。第1列,等分成上下两部分,第一部分的前半部分为0,后半部分为1。第二部分的前半部分为1,后半部分为0。
后面继续看,可以看出规律了。把第i列分成2^i部分,奇数部分的前半部分为0,后半部分为1,偶数部分的前半部分为1,后半部分为0。或者用另外一种表述方法,我们可以把本次的划分看作前一次的划分的
一个部分,如果是上次划分的前半部分,则符合前面的奇数部分。后半部分则符合前面的后半部分。代码如下:
 1 /*
 2 使用分治法,如果本次属于前一次二分的前半部分,则本次的前半部分第n位填0,后半部分第n位填1
 3             如果本次属于前一次二分的后半部分,则本次的前半部分第n位填1,后半部分第n位填0
 4 第一次填写,设为前半部分。代码中left代表前半部分-_-。
 5 */
 6 
 7 void setGray(int *num, int start, int end, bool left, int n)
 8 {
 9     int lbit, rbit, i = 0;
10     int mid = (start + end) >> 1;
11 
12     if (left)
13     {
14         lbit = 0;
15         rbit = 1 << n;
16     }
17     else
18     {
19         lbit = 1 << n;
20         rbit = 0;
21     }
22 
23     for (i = start; i <= mid; ++i)
24         num[i] = num[i] | lbit;
25 
26     for (i = mid + 1; i <= end; ++i)
27         num[i] = num[i] | rbit;
28 
29     if (n > 0)
30     {
31         setGray(num, start, mid, true, n - 1);
32         setGray(num, mid + 1, end, false, n - 1);
33     }
34 }
35 
36 
37 int *grayCode(int n, int *returnSize)
38 {
39     *returnSize = 1 << n;
40     int *ans = (int *)malloc(*returnSize * sizeof(int));
41     int i = 0;
42     for (i = 0; i < *returnSize; ++i)
43     {
44         ans[i] = 0;
45     }
46     if (n > 0) setGray(ans, 0, *returnSize - 1, true, n - 1);
47     return ans;
48 }
原文地址:https://www.cnblogs.com/DennisXie/p/4792928.html