LeetCode-89-Gray Code

Posted 无名路人甲

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode-89-Gray Code相关的知识,希望对你有一定的参考价值。

算法描述:

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:

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

For a given n, a gray code sequence may not be uniquely defined.
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 the gray code sequence to begin with 0.
             A gray code sequence of n has size = 2n, which for n = 0 the size is 20 = 1.
             Therefore, for n = 0 the gray code sequence is [0].

解题思路:最高位或1.

0

1 // 第一轮0 | 1 << 0

 

00  

01

11 //第二轮 保留第一轮原有数字,并添加新数字--即在现有数字最高位或1

10

 

000

010

011

010

100  //第三轮 保留第二轮所有数字,并添加新数字--数字最高位或1

110

111

110

从后往前添加是为了不让后面添加的数对原有元素进行干扰。

    vector<int> grayCode(int n) {
        vector<int> results;
        results.push_back(0);
        for(int i=0; i < n; i++){
            for(int j=results.size()-1; j >= 0; j--){
                results.push_back(results[j] | 1 << i);
            }
        }
        return results;
    }

 

以上是关于LeetCode-89-Gray Code的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode89 Gray Code

LeetCode-89-Gray Code

Leetcode 89. Gray Code

leetcode 89 Gray Code ----- java

[LeetCode] 89. Gray Code

[LeetCode] 89. Gray Code 格雷码