Description
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.
Example 1:
1 | Input: 2 |
Example 2:
1 | Input: 0 |
解法
题意是每次只允许变动一位,根据给出的位数得到序列。我采用的是最原始的深度优先搜索算法,利用hash表不能重复的性质解这道题,每次在写深度优先搜索的时候注意回溯的处理。
具体代码如下:
1 | class Solution { |