我的思路是从0,1开始拼接,因为格雷码除了第一位,后面的n-1位都是呈对称分布,所以使用递归来拼接,会非常简单。
代码如下:
/**
* Created with IntelliJ IDEA.
* Description:
* User: Y
* Date: 2019-07-15
* Time: 10:22
*/
import java.util.*;
public class GrayCode {
public static String[] getGray(int n) {
String[] s = new String[(int) Math.pow(2, n)];
if(n == 1) {
s[0] = "0";
s[1] = "1";
return s;
}
String[] last = getGray(n-1);
for(int i = 0; i < last.length; i++) {
s[i] = "0" + last[i];
s[s.length - 1 - i] = "1" + last[i];
}
return s;
}
public static void main(String[] args) {
System.out.println(Arrays.deepToString(getGray(4)));
}
}
下面是运行结果: