[leetcode] 89. 格雷编码

89. 格雷编码

这个题挺有意思,意思就是让你生成2^n个数,但是相邻的两数之间的二进制编码只能有一处不同,比如100 与 101,但是100,110就不行

多写几个数就找到规律了,比如当n=3时:
0
1
11
10
110
111
101
100

观察发现,第5个数其实就是第4个数在前面加了个1,而第6个数就是第3个数在前面+1,依次类推....可由前4个数得到n=3时的4个数

当n=4时,应该会有2^(n-1) = 8个数,这8个数也就是可由n=3时得到的8个数前面+1而得

完全就是个找规律题。。不知道leetcode怎么这么多人点👎

class Solution {
    public static String stringRepeat(int count, String with) {
        return new String(new char[count]).replace("\0", with);
    }

    public List<Integer> grayCode(int n) {
        List<String> f = new ArrayList<>();
        f.add("0");
        f.add("1");
        f.add("11");
        f.add("10");
        int top = 3;
        for (int i = 3; i <= n; i++) {
            int k = ((Double) Math.pow(2, i - 1)).intValue();
            for (int j = 0; j < k / 2; j++) {
                String tmp = "1";
                tmp += f.get(top - j);
                f.add(tmp);
            }

            for (int j = (k / 2); j < k; j++) {
                String tmp = "1";
                String s = f.get(top - j);
                tmp += stringRepeat(i - s.length() - 1, "0") + s;
                f.add(tmp);
            }
            top += k;
        }
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < Math.pow(2, n); i++) {
            list.add(Integer.valueOf(f.get(i), 2));
        }
        return list;
    }
}
posted @ 2018-08-05 22:35  ACBingo  阅读(546)  评论(0编辑  收藏  举报