[LeetCode]Gray Code

Posted 乘风有时

tags:

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

题目:Gray Code

给定格雷码的位数,输出所有的格雷码对应的十进制数。

思路:

000 0

001 1

011 3

010 2

110 6

111 7

101 5

100 4

前四个和后四个的前两位对称,前两个和后两个的第一位是对称的。

如此,可看出,格雷码有一定的对称性。

package com.example.medium;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 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.
 * 
 * For example, given n = 2, return [0,1,3,2]. Its gray code sequence is:
 * 
 * 00 - 0
 * 01 - 1
 * 11 - 3
 * 10 - 2
 * Note:
 * For a given n, 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.
 * 
 * For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that.
 * @author FuPing
 *
 */
public class GrayCode {
    private void getCode(List<Integer> list,int start,int end,int value){
        if(start == end){//第一个
            list.add(0, 0);
            return;
        }
        int mid = (start + end)/2;
        getCode(list, start, mid, value);//递归求前半部分

        for (int i = mid + 1; i <= end; i++) {//对称性
            list.add(i, list.get(end - i) + (end - start + 1)/2);
        }
    }
    public List<Integer> grayCode(int n) {
        int length = (int)Math.pow(2, n);
        List<Integer> list = new ArrayList<Integer>(length);
        getCode(list, 0, length - 1, 0);

        return list;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println(new GrayCode().grayCode(7));

    }

}
class Solution {
public:
    vector<int> grayCode(int n) {
        vector<int> codes;
        getGrayCode(codes, 0, pow(2, n));
        return codes;
    }
private:
    void getGrayCode(vector<int> &grayCodes, int start, int length){
        if (length == 1){
            grayCodes.push_back(0);
            return;
        }
        getGrayCode(grayCodes,0,length/2);
        for (int i = length/2; i < length; i++)
        {
            grayCodes.push_back(grayCodes.at(length - i - 1) + length/2);
        }
    }
};

 

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

[LeetCode][JavaScript]Gray Code

Leetcode 89. Gray Code

LeetCode89 Gray Code

LeetCode——Gray Code

LeetCode: Gray Code [089]

LeetCode-89-Gray Code