题解 | #生成格雷码#
生成格雷码
https://www.nowcoder.com/practice/50959b5325c94079a391538c04267e15
import java.util.*;
public class GrayCode {
public String[] getGray(int n) {
// write code here
// n为格雷码 由n-1位的格雷码生成
// 比如n=3的格雷码是n=2的格雷码的首位添加0或1生成的,正序添加1之后,反序添加0
String[] resStrs = null;
if (n == 1) {
resStrs = new String[] {"0", "1"};
} else {
String[] strs = getGray(n - 1);
resStrs = new String[2 * strs.length];
for (int i = 0; i < strs.length; i++) {
resStrs[i] = "0" + strs[i];
resStrs[resStrs.length - 1 - i] = "1" + strs[i];
}
}
return resStrs;
}
}