89 Gray Code

1. Question

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

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

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

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

Note: For a givenn, 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.

2. Implementation

(1) Backtracking

思路: 本质上和320 Generalized Abbreviation一样,对每个bit,我们有两种选择,要么不改变原有的bit,要么反转现有的bit

class Solution {
    public List<Integer> grayCode(int n) {
        List<Integer> res = new ArrayList<>();
        int[] num = new int[1];
        getGrayCode(n, num, res);
        return res;
    }

    public void getGrayCode(int n, int[] num, List<Integer> res) {
        if (n == 0) {
            res.add(num[0]);
            return;
        }
        // For each bit of the num, we either leave it alone or invert the current bit
        // Leave the current bit alone
        getGrayCode(n - 1, num, res);

        // Invert the current bit
        num[0] ^= (1 << (n -1));
        getGrayCode(n - 1, num, res);
    }
}

3. Time & Space Complexity

Backtracking: 时间复杂度O(2^n), 空间复杂度O(2^n)

Last updated