89. Gray Code - jiejackyzhang/leetcode-note GitHub Wiki

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.

解题思路为backtracking。

##Approach 1: recursive 这里需注意的是要把bits设为全局变量,这样它的值始终是前次调用helper的值,每次翻转前一次值的一位。

public class Solution {
    
    private int bits = 0;
    
    public List<Integer> grayCode(int n) {
        List<Integer> res = new ArrayList<Integer>();
        helper(n, res);
        return res;
    }
    
    private void helper(int k, List<Integer> res) {
        if(k == 0) {
            res.add(bits);
        } else {
            helper(k-1, res);
            bits ^= (1 << (k-1));
            helper(k-1, res);
        }
    }
}

##Approach 2: iterative 这里用到的思想是每次都在已存在的数中按倒序往前一位加1。 因为已存在的数是符合grey code的,因此后面的数最高位都是1,其余各位与已存在的数保持一致,因此也符合grey code。

public class Solution {
    public List<Integer> grayCode(int n) {
        List<Integer> res = new ArrayList<Integer>();
        res.add(0);
        for(int i = 0; i < n; i++) {
            int inc = (1 << i);
            for(int j = res.size()-1; j >= 0; j--) {
                res.add(res.get(j) + inc);
            }
        }
        return res;
    }
}
⚠️ **GitHub.com Fallback** ⚠️