[Leetcode] 89. Gray code (Gray code + bit operation + simulation)

Title description

Gray coding is a binary number system in which two consecutive values ​​differ by only one digit.
Given a non-negative integer n representing the total number of digits in the code, print its Gray code sequence. Even if there are multiple different answers, you only need to return one of them.
The Gray code sequence must start 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] is also a valid Gray code sequence.
00 - 0
10 - 2
11 - 3
01 - 1

Example 2:

Input: 0
Output: [0]
Explanation: We define Gray code sequence must start with 0.
Given a Gray code sequence with a total number of digits of n, its length is 2n. When n = 0, the length is 20 = 1.
Therefore, when n = 0, its Gray code sequence is [0].

Topic link: 89. Gray coding

Ideas:

  • First, we must understand the construction method of the Gray code: known iii -digit Gray code, just putiiAfter i -bit Gray code is mirrored, fill in 0 in the front of the first half and add 1 in front of the second half to geti + 1 i+1i+1 Gray code.

  • Since the output in the title is a decimal number represented by Gray code, and adding 0 to the front does not change the decimal number, so i + 1 i+1i+The first half of the 1 -digit Gray code andiiThe i -bit Gray code is consistent.

  • The final approach is to construct 0, 1, 2, ⋅ ⋅ ⋅, n 0, 1, 2, ···, n step by step012, N -bit Gray code,iiThe i -bit Gray code only needs to bei − 1 i-1iAddi <<1 toeach number of 1 -digit Gray codei<<1i<<1 (play theiiThe i position is 1) and add it to the answer array by mirroring.

  • The gray code mirror construction method is as follows, where the binary number is the corresponding decimal number:

1 digit Gray code 2-digit Gray code 3-digit Gray code 4-digit Gray code
0(0) 00(0) 000(0) 0000(0)
1(1) 01(1) 001(1) 0001(1)
11(3) 011(3) 0011 (3)
10(2) 010(2) 0010(2)
110(6) 0110(6)
111(7) 0111(7)
101 (5) 0101(5)
100(4) 0100(4)
1100(12)
1101(13)
1111(15)
1110(14)
1010(10)
1011(11)
1001(9)
1000(8)

C++ code:

class Solution {
    
    
public:
    vector<int> grayCode(int n) {
    
    
    vector<int>res(1<<n,0);   //n位格雷码有2^n个元素
    int i=0,p=0;     //i表示第i位格雷码,p表示“镜像的分界面”       
    while(i<n){
    
    
    for(int l=p,r=p+1;l>=0;l--,r++){
    
    
    res[r]=res[l]+(1<<i);  //将l处的元素前面添1放到镜像r处 
    }
    i++;          //增加“格雷码位数"
    p=(1<<i)-1;   //更新“分界面”
    }
    return res;
    }
};

Guess you like

Origin blog.csdn.net/IAMLSL/article/details/115268874