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
题意:给定一个bit位数返回一组灰度码,灰度码的意思是每两个相邻的码之间有且只有一位不同,比如00010,00110,这对码之间只有第三位不同。
分析:我们看到的这题的tag是backtracking,但是鄙人才疏学浅没有想到合适写法来写出这个回溯来,于是乎选择了最笨的办法,从最简单的1位开始想,
首先看当n = 1时的情况,非常简单的就可以得出来0,1;
当n = 2时,
00
01
11
10(此时还没有特别明显的规律);
当n = 3时,
三位 后两位 十进制
000 00 0
001 01 1
011 11 3
010 10 2
110 10 2
111 11 3
101 01 1
100 00 0
此时我们可以看后两位,可以看出来,n=3时的灰度码有8个,前四个换算成十进制跟n=2时是一样的,而后四个的最后两位,换算成十进制就正好等于n=2时的倒序,其中的道理也很简单,我们既然得到了n=2的时候的灰度码序,那么再倒过来一遍,然后第一位补上1,就可以得出n=3的灰度码序。
代码实现:
public class Solution
{
public List<int> GrayCode(int n)
{
List<int> ret = new List<int>();
ret.Add(0);
if (n == 0)
return ret;
ret.Add(1);
for (int i = 2; i <= n; i++)
{
int tmp = (int)Math.Pow(2, i - 1);
for (int j = tmp - 1; j >= 0; j--)
{
ret.Add(ret[j] + tmp);
}
}
return ret;
}
}