Leetcode 89. Gray Code

版权声明:博客文章都是作者辛苦整理的,转载请注明出处,谢谢! https://blog.csdn.net/Quincuntial/article/details/83348109

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Gray Code

2. Solution

  • Version 1
class Solution {
public:
    vector<int> grayCode(int n) {
        vector<int> result;
        bitset<32> code;
        traverse(result, code, n - 1);
        return result;
    }

private:
    void traverse(vector<int>& result, bitset<32>& code, int pos) {
        if(pos < 0) {
            int value = code.to_ulong();
            result.push_back(value);
            return;
        }
        traverse(result, code, pos - 1);
        code.flip(pos);
        traverse(result, code, pos - 1);
    }
};
  • Version 2
class Solution {
public:
    vector<int> grayCode(int n) {
        vector<int> result;
        int code = 0;
        traverse(result, code, n - 1);
        return result;
    }

private:
    void traverse(vector<int>& result, int& code, int pos) {
        if(pos < 0) {
            result.push_back(code);
            return;
        }
        traverse(result, code, pos - 1);
        code ^= (1 << pos);
        traverse(result, code, pos - 1);
    }
};

Reference

  1. https://leetcode.com/problems/gray-code/description/

Gray code

10-30

Problem DescriptionnThe reflected binary code, also known as Gray code after Frank Gray, is a binary numeral system where two successive values differ in only onebit (binary digit). The reflected binary code was originally designed to prevent spurious output from electromechanical switches. Today, Gray codes are widely used to facilitate error correction in digital communications such as digital terrestrial television and some cable TV systems.nn![](http://acm.hdu.edu.cn/data/images/5375-1.jpg)nnnNow , you are given a binary number of length n including ‘0’ , ’1’ and ‘?’(? means that you can use either 0 or 1 to fill this position) and n integers(a1,a2,….,an) . A certain binary number corresponds to a gray code only. If the ith bit of this gray code is 1,you can get the point ai.nCan you tell me how many points you can get at most?nnFor instance, the binary number “00?0” may be “0000” or “0010”,and the corresponding gray code are “0000” or “0011”.You can choose “0000” getting nothing or “0011” getting the point a3 and a4.n nnInputnThe first line of the input contains the number of test cases T.nnEach test case begins with string with ‘0’,’1’ and ‘?’.nnThe next line contains n (1<=n<=200000) integers (n is the length of the string).nna1 a2 a3 … an (1<=ai<=1000)n nnOutputnFor each test case, output “Case #x: ans”, in which x is the case number counted from one,’ans’ is the points you can get at mostn nnSample Inputn2n00?0n1 2 4 8n????n1 2 4 8n nnSample OutputnCase #1: 12nCase #2: 15

没有更多推荐了,返回首页

私密
私密原因:
请选择设置私密原因
  • 广告
  • 抄袭
  • 版权
  • 政治
  • 色情
  • 无意义
  • 其他
其他原因:
120
出错啦
系统繁忙,请稍后再试