在一组数的编码中,若任意两个相邻的代码只有一位二进制数不同, 则称这种编码为格雷码(Gray Code),
请编写一个函数,使用递归的方法生成N位的格雷码。
给定一个整数n,请返回n位的格雷码,顺序为从0开始。
public class 生成格雷码 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
sc.close();
String[]res=getGray(n);
for(String str:res){
System.out.print(str+" ");
}
}
public static String[] getGray(int n) {
String[] code = new String[(int)Math.pow(2,n)];
if (n == 1){
code[0] = "0";
code[1] = "1";
return code;
}
String[] last = getGray(n-1);//code长度刚好是last的两倍
for (int i = 0; i < last.length;i++){//拼接,前半段为0,后半段为1
code[i] = "0"+last[i];
code[code.length-i-1] = "1" + last[i];
}
return code;
}
}