leetcode 89. Gray code

Gray code is a binary number system, in this system, only two successive values ​​of a difference in number of bits.

Given a total number of bits representing an encoded non-negative integer n, which is the print gray coding sequence. Gray coding sequence must begin with 0.

Example 1:

Input: 2
Output: [0,1,3,2]
Explanation:
00 - 0
01 -. 1
. 11 -. 3
10 - 2

For a given n, which is not unique Golay coding sequence.
For example, [0,2,3,1] Gray coding is also a valid sequence.

00 - 0
10 - 2
. 11 -. 3
01 -. 1
Example 2:

Input: 0
Output: [0]
Explanation: We define Golay coding sequence must start with 0.
  The total number of bits to encode a given Golay coding sequence of n, has a length of 2n. When n = 0, length 20 = 1.
  Thus, when n = 0, which is a Gray code sequence [0].

class Solution: 
    DEF GrayCode (Self, n-: int ) -> List [ int ]: 
        RES = [ 0 ] 
        I = 0 
        the while I < n-: # 2 starts from 0 th, 
            res_inv = RES [:: - . 1 ] # res reverse seeking List 
            res_inv = [X + POW ( 2 , I) for X in res_inv] 
            res = res + res_inv 
            I + = . 1 
        return res

 

Guess you like

Origin www.cnblogs.com/xiaotongtt/p/11318383.html