zoukankan      html  css  js  c++  java
  • 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.

    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.


    //整数n 的格雷码是n ^ (n/2)。

    class Solution {
    public:
        vector<int> grayCode(int n) {
            vector<int> rst;
    		size_t size = 1 << n;//2^n
    		rst.reserve(size);
    		for (size_t i = 0; i < size; i++)
    			rst.push_back(i ^ (i >> 1));
    		return  rst;
        }
    };


    vector的reserve()与resize()函数差别:

    • vector 的reserve增加了vector的capacity,可是它的size没有改变!

      而resize改变了vector的capacity同一时候也增加了它的size!

    • reserve是容器预留空间。但在空间内不真正创建元素对象,所以在没有增加新的对象之前,不能引用容器内的元素。增加新的元素时,要调用push_back()/insert()函数。
    • resize是改变容器的大小,且在创建对象,因此,调用这个函数之后。就能够引用容器内的对象了,因此当增加新的元素时,用operator[]操作符,或者用迭代器来引用元素对象。此时再调用push_back()函数。是加在这个新的空间后面的。

  • 相关阅读:
    QBoxLayout中setSpacing(int)和addSpacing(int)的区别
    BZOJ1017 树形DP
    树形DP 2415HDU
    树形DP基础题 HDU1520
    最小生成树个数 并查集压缩路径
    伸展树基本概念基本题目
    BZOJ1010单调性DP优化
    BZOJ1009 矩阵快速幂+DP+KMP
    字典树(数组实现)
    poj 1611 The Suspects(并查集输出集合个数)
  • 原文地址:https://www.cnblogs.com/llguanli/p/6839715.html
Copyright © 2011-2022 走看看