89 Gray Code
Last updated
Was this helpful?
Last updated
Was this helpful?
Was this helpful?
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.
(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[
Backtracking: 时间复杂度O(2^n), 空间复杂度O(2^n)