[编程题]-生成格雷码
【解题思路】:
递归的思路是
n
位
gray
码是由
n-1
位
gray
码生成,举个例子简单一些:
比如求
n=3
的
gray
码,首先知道
n=2
的
gray
码是
(00,01,11,10)
那么
n=3
的
gray
码其实就是对
n=2
的
gray
码首位添加
0
或
1
生成的,添加
0
后变成
(000,001,011,010)
添加
1
后需要顺序反向就变成
(110,111,101,100)
组合在一起就是
(000,001,011,010,110,111,101,100)
【示例代码】:
import java.util.*;
public class GrayCode {
public String[] getGray(int n) {
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;
}
}