##LeetCode—89. Gray Code
####题目
https://leetcode.com/problems/gray-code/description/
给出n,生成n个比特的二进制数,这些数组成格雷码。对格雷码不太了解的同学,百度一下。
####解法及思路
这道题也是一道寻找规律的题目,如果对格雷码非常了解,可以很轻松的找到规律,并写出代码
我们可以多写几个例子出来找规律。n=3时:
0 0 0 - 0
0 0 1 - 1
0 1 1 - 3
0 1 0 - 2
1 1 0 - 6
1 1 1 - 7
1 0 1 - 5
1 0 0 - 4
可以看到由四位变到八位时,
6 = 2 + 4;
7 = 3 + 4;
5 = 1 + 4;
4 = 0 + 4;
也就是格雷码的镜像性质,n位的格雷码可以由n-1位的格雷码通过上下镜像的方式得到,并且相互成为镜像的两数之间相差的长度len恰好是
2
n
2^n
2n
这样我们就可以轻松地写出代码了
####代码
class Solution {
public List<Integer> grayCode(int n) {
List<Integer> list = new ArrayList<Integer>();
list.add(0);
for(int i=0; i<n; i++){
int len = (int) Math.pow(2, i);
for(int j=len-1; j>=0; j--){
int a = list.get(j);
list.add(a+len);
}
}
return list;
}
}