89 Gray Code

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:
1
00 - 0
2
01 - 1
3
11 - 3
4
10 - 2
Copied!
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
1
class Solution {
2
public List<Integer> grayCode(int n) {
3
List<Integer> res = new ArrayList<>();
4
int[] num = new int[1];
5
getGrayCode(n, num, res);
6
return res;
7
}
8
9
public void getGrayCode(int n, int[] num, List<Integer> res) {
10
if (n == 0) {
11
res.add(num[0]);
12
return;
13
}
14
// For each bit of the num, we either leave it alone or invert the current bit
15
// Leave the current bit alone
16
getGrayCode(n - 1, num, res);
17
18
// Invert the current bit
19
num[0] ^= (1 << (n -1));
20
getGrayCode(n - 1, num, res);
21
}
22
}
Copied!

3. Time & Space Complexity

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