题解 | #生成格雷码#

生成格雷码

http://www.nowcoder.com/practice/50959b5325c94079a391538c04267e15


public class GrayCode {
    public String[] getGray(int n) {
        // write code here
        if (n == 1) {//递归终止条件
            String[] gray = new String[2];
            gray[0] = "0";
            gray[1] = "1";
            return gray;
        }
        String[] temp = getGray(n - 1);
        String[] res = new String[temp.length * 2]; //单层递归逻辑
        for (int i = 0; i < temp.length; i++) {
            res[i] = "0" + temp[i];
        }
        for (int i = 0; i < temp.length ; i++) {
            res[i + temp.length] = "1" + temp[temp.length - i - 1];
        }
        return res;
    }
}
全部评论

相关推荐

点赞 评论 收藏
分享
2 收藏 评论
分享
牛客网
牛客企业服务