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:
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
3. Time & Space Complexity
Backtracking: 时间复杂度O(2^n), 空间复杂度O(2^n)
Last updated