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()函数。是加在这个新的空间后面的。

  • 相关阅读:
    【递推】【概率】Gym
    【坐标变换】【二维偏序】【线段树】Gym
    【DLX算法】hdu3498 whosyourdaddy
    【DLX算法】poj2676 Sudoku
    【Pollard-rho算法】【DFS】poj2429 GCD & LCM Inverse
    Pollard-rho算法:模板
    【筛法求素数】【推导】【组合数】UVALive
    【二项式定理】【DFS】UVALive
    【并查集】【枚举倍数】UVALive
    【Floyd算法】Gym
  • 原文地址:https://www.cnblogs.com/llguanli/p/6839715.html
Copyright © 2011-2022 走看看