89. Gray Code

Description

The gray code is a binary numeral system where two successive values differ in only one bit.

Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.

For example, given n = 2, return [0,1,3,2]. Its gray code sequence is:

00 - 0
01 - 1
11 - 3
10 - 2

Note:
For a given n, a gray code sequence is not uniquely defined.

For example, [0,2,3,1] is also a valid gray code sequence according to the above definition.

For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that.

Solution

DFS

找规律呀。

class Solution {
    public List<Integer> grayCode(int n) {
        if (n < 0) {
            return Collections.EMPTY_LIST;
        }
        
        return grayCodeRecur(n);
    }
    
    public List<Integer> grayCodeRecur(int n) {
        List<Integer> codes = new ArrayList<>();

        if (n == 0) {
            codes.add(0);
            return codes;
        }

        List<Integer> subCodes = grayCodeRecur(n - 1);
        codes.addAll(subCodes);
        int delta = 1 << (n - 1);
        
        for (int i = subCodes.size() - 1; i >= 0; --i) {
            codes.add(delta + subCodes.get(i));
        }
        
        return codes;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容