格雷码的递归实现
题目
产生n位元的所有格雷码。
格雷码相关
1,定义:在一组数的编码中,若任意两个相邻的代码只有一位二进制数不同,则称这种编码为格雷码(Gray Code),另外由于最大数与最小数之间也仅一位数不同,即“首尾相连”,因此又称循环码或反射码。
2,
解
public static String[] grayCode(int n){
String[] graycode=new String[(int)Math.pow(2, n)];
if(n==1){
graycode[0]="0";
graycode[1]="1";
return graycode;
}
String[] last=grayCode(n-1);
for(int i=0;i<last.length;i++){
graycode[i]="0"+last[i];
graycode[graycode.length-1-i]="1"+last[i];
}
return graycode;
}
小结
1,Math.pow(m,n),即m^n;
2,Arrays.toString(arr),即输出arr数组中的元素;
3,递归的时候,一定要注意最后的返回。